初学Hibernate,简单实现单表的增删查改

因为maven有很好的传递依赖,管理jar包的能力,因此就通过maven来进行Hibernate的学习。

1.环境的搭建

新建一个meven项目

 1.jar包配置

Hibernate所依赖的jar包都配置到pom.xml中,具体配置如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.grganking</groupId>
    <artifactId>hibernate</artifactId>
    <version>1.0.0-SNAPSHOT</version>

<build>
        <!-- we dont want the version to be part of the generated war file name -->
        <finalName>${artifactId}</finalName>
    </build>
    <dependencies>
    <!-- test 待用-->
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.7.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- 采用MySQL数据库 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.5</version>
        </dependency>
        <!-- Hibernate的核心依赖 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.2.Final</version>
        </dependency>
        <!-- Because this is a web app, we also have a dependency on the servlet 
            api. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
        </dependency>
        <!-- Hibernate uses slf4j for logging, for our purposes here use the simple 
            backend -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.21</version>
        </dependency>
        <!-- Hibernate gives you a choice of bytecode providers between cglib and 
            javassist -->
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>
    </dependencies>
</project>
2.数据库设计
新建一个单表EVENTS
CREATE TABLE `events` (
  `event_id` varchar(50) NOT NULL,
  `titles` varchar(32) DEFAULT NULL,
  `date` date DEFAULT NULL,
  PRIMARY KEY (`event_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.Hibernate配置文件Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <!--下面是数据库的基本连接信息,对一个应用来说,设置一个session-factory节点就够了,除非我们中间使用了多个数据库 -->
    <session-factory>
        <!--数据库驱动信息 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!--url信息 -->
        <property name="connection.url">jdbc:mysql://localhost:3306/study</property>
        <!--用户名 -->
        <property name="connection.username">root</property>
        <!--密码 -->
        <property name="connection.password">****</property>
        <!--数据库方言信息 -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <!-- 在日志中显示sql语句,方便学习 -->
        <property name="hibernate.show_sql">true</property>  
        <property name="hibernate.format_sql">true</property> 
        <!--指定Hibernate映射文件路径 -->
        <mapping resource="org/grgbanking/mapping/EventMapping.xml" />

    </session-factory>

</hibernate-configuration> 

3.编写

1.实体类
新建一个实体类。最好与数据库表中的字段保持一致,防止出错。有set和get方法,无参的构造方法
package org.grgbanking.pojo;

import java.util.Date;
/**
 * 
 * @author cjyun
 * @date 2016年11月22日
 */
public class Event {
    private String id;
    private String titles;
    private Date date;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTitles() {
        return titles;
    }
    public void setTitles(String titles) {
        this.titles = titles;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    public Event() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Event(String id, String titles, Date date) {
        super();
        this.id = id;
        this.titles = titles;
        this.date = date;
    }

}

2.实体类的映射mapping配置文件EventMapping.xml

<?xml version="1.0" encoding="UTF-8"?>
<hibernate-mapping package="org.grgbanking.pojo">
    <class name="Event" table="EVENTS">
        <id name="id" column="EVENT_ID">

        </id>
        <property name="date" type="timestamp" column="DATE" />
        <property name="titles" />
    </class>

</hibernate-mapping>

配置完成以后,别忘了在Hibernate的配置文件中添加映射

 <mapping resource="org/grgbanking/mapping/EventMapping.xml" />

3.建立Hibernate工具类进行创建sessionfactory

package org.grgbanking.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * 
 * @author cjyun
 * @date 2016年11月22日
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable  ex) {
            System.err.println("Initial SssionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }

    }

    public static SessionFactory getSessionfactory() {
        return sessionFactory;
    }

}

4.测试

编写一个简单的main方法
package org.grgbanking.util;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;

import org.apache.catalina.startup.ContextConfig;
import org.grgbanking.pojo.Event;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class EventManager {


    public static void main(String[] args) {

        //建立sessionfactory
        SessionFactory  sessionFactory = HibernateUtil.getSessionfactory();
         //取得session  
        Session session = null;

        session = sessionFactory.openSession();

        UUID id = UUID.randomUUID();

        Event mgr = new Event();
        mgr.setId(id+"");
        mgr.setDate(new Date());
        mgr.setTitles("MyEvent");


        try {  

            //开启事务  
            session.beginTransaction();  


            //保存Event对象  
            session.save(mgr);  
            Event mgr1 = new Event();
            //删除对象
            mgr1.setId("4efde32c-c98b-42ae-9f93-14cc95583502");
            session.delete(mgr1);
            //查找
            Event u1=(Event)session.load(Event.class,  mgr.getId());  
            System.out.println("从数据库加载数据的用户名为-------"+u1.getTitles()); 
            //更改
            mgr.setTitles("ALLEvents");
            session.update(mgr);
            u1=(Event)session.load(Event.class,  mgr.getId());
            System.out.println("从数据库加载数据的用户名为-----"+u1.getTitles()); 
            //提交事务  
            session.getTransaction().commit();  
        }catch(Exception e) {  
            e.printStackTrace();  
            //回滚事务  
            session.getTransaction().rollback();  
        }finally {  
            if (session != null) {  
                if (session.isOpen()) {  
                    //关闭session  
                    session.close();  
                }  
            }  
        }
    }



}

5.总结

添加一个日志文件可以更好地观察流程,Hibernate方便的是不用自己书写sql 语句。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值