hibernate添加数据入门小案例

1.建立一个java项目,在目录下新建一个lib文件夹引入hibernate架包如图所示:

2. 新建com.LHB.domain包,在包中分别创建一个Employee.java和Employee.hbm.xml文件,

Employee.java中的代码如下:

 1 package com.LHB.domain;
 2 
 3 import java.util.Date;
 4 //该pojo/javabean/domain按照规范应当序列化,目的是可以唯一的表示该对象呢,同时可以在网络和文件传输
 5 public class Employee implements java.io.Serializable {
 6     private static final long serialVersionUID = 1L;
 7     private Integer id;
 8     private String name;
 9     private String email;
10     private Date hiredate;
11     public Integer getId() {
12         return id;
13     }
14     public void setId(Integer id) {
15         this.id = id;
16     }
17     public String getName() {
18         return name;
19     }
20     public void setName(String name) {
21         this.name = name;
22     }
23     public String getEmail() {
24         return email;
25     }
26     public void setEmail(String email) {
27         this.email = email;
28     }
29     public Date getHiredate() {
30         return hiredate;
31     }
32     public void setHiredate(Date hiredate) {
33         this.hiredate = hiredate;
34     }
35     
36 }

Employee.hbm.xml映射文件配置如下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!-- 映射文件通过DTD来指定格式 -->
 3 <!DOCTYPE hibernate-mapping PUBLIC 
 4     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 5     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 6 <!-- 该文件用于配置domain对象和表的映射关系 -->
 7 <hibernate-mapping package="com.LHB.domain">
 8     <class name="Employee" table="employee" >
 9         <!-- id元素用于指定主键属性 -->
10         <!-- 
11         <id name="id" column="id" type="java.lang.Integer">
12             该元素用来指定主键生成的策略hilo native increment sequence uuid
13             <generator class="sequence">
14                 <param name="sequence">emp_seq</param>
15             </generator>
16         </id>
17          -->
18          <!-- 在更改数据库时对主键生成策略做了修改 -->
19          <id name="id" column="id" type="java.lang.Integer">
20              <generator class="increment"></generator>
21          </id> 
22         <!-- 如果id号希望用户自己设定,而不是由数据库MySQL -->
23        <!--  <id name="id" column="id" type="java.lang.Integer">
24             <generator class="assigned"/>
25         </id> -->
26         <!-- 对其它属性还要配置 -->
27         <property name="name" type="java.lang.String">
28             <column name="name" not-null="false"  />
29         </property>
30         <property name="email" type="java.lang.String">
31             <column name="email" not-null="false" />
32         </property>
33         <property name="hiredate" type="java.util.Date">
34             <column name="hiredate" not-null="false" />
35         </property>
36     </class>
37     
38 
39 </hibernate-mapping>

3.在项目src文件下创建hibernate.cfg.xml配置文件,其中的配置信息如下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 
 6 <hibernate-configuration>
 7     <session-factory>
 8         <!-- 配置使用的driver -->
 9         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
10         <property name="connection.username">root</property>
11         <property name="connection.password">123456</property>
12         <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
13         <!-- 配置dialect方言,明确告诉hibernate连接哪种数据库 -->
14         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
15         <!-- 显示出对应的sql语句 -->
16         <property name="show_sql">true</property>
17         <!-- 让hibernate给我们自动创建表  creat:如果mysql中没有该表则创建,如果有表则删除再创建
18              update:如果没有表则创建新表,如果有表则看表结构有没有变化,如果有变化则创建新表-->
19         <property name="hbm2ddl.auto">update</property>
20         <!-- 指定管理的对象映射文件 -->
21         <mapping resource="com/LHB/domain/Employee.hbm.xml"/>
22         
23     </session-factory>
24 </hibernate-configuration>

4. 创建一个测试类TestMain

  1 package com.LHB.view;
  2 
  3 import java.util.Date;
  4 
  5 import org.hibernate.SessionFactory;
  6 import org.hibernate.Transaction;
  7 import org.hibernate.cfg.Configuration;
  8 import org.hibernate.classic.Session;
  9 
 10 import com.LHB.domain.Employee;
 11 import com.LHB.util.MySessionFactory;
 12 
 13 public class TestMain {
 14 
 15     public static void main(String[] args) {
 16         // TODO Auto-generated method stub
 17 
 18         updateEmp();
 19         //addEmployee();
 20     }
 21     /**
 22      * 删除用户
 23      */
 24     private static void delEmp() {
 25         //删除
 26         //获取一个session
 27         Session session = MySessionFactory.getSessionFactory().openSession();
 28         Transaction transaction = session.beginTransaction();
 29         try {
 30             //修改1.先获取该雇员,然后删除
 31             Employee employee=(Employee) session.load(Employee.class, new Integer(3));
 32             session.delete(employee);
 33             transaction.commit();
 34             session.close();
 35             
 36         }catch (Exception e) {
 37             if(transaction!=null) {
 38                 transaction.rollback();
 39             }
 40             
 41             throw new RuntimeException(e.getMessage());
 42         } finally {
 43             //关闭session
 44             if(session!=null&&session.isOpen()) {
 45                 session.close();
 46             }
 47             
 48         }
 49     }
 50     /**
 51      * 更新用户
 52      */
 53     private static void updateEmp() {
 54         //修改用户
 55         //获取一个会话
 56         /*Session session = MySessionFactory.getSessionFactory().openSession();
 57         
 58         Transaction transaction = session.beginTransaction();
 59         //修改用户1.获取要修改的用户,2.修改
 60         //load是可以通过主键属性,获取该对象实例,《----》表的记录对应
 61         Employee employee = (Employee)session.load(Employee.class, new Integer(3));
 62         employee.setName("张三");
 63         transaction.commit();
 64         session.close();
 65         */
 66         //添加事务回滚优化之后
 67         Session session = MySessionFactory.getSessionFactory().openSession();
 68         Transaction transaction = null;
 69         try {
 70             transaction = session.beginTransaction();
 71             //do...
 72             Employee employee = (Employee)session.load(Employee.class, new Integer(1));
 73             //用户指定id号
 74             //employee.setId(new Integer(100));
 75             employee.setName("李四");
 76             employee.setEmail("lisi@sohu.com");
 77             
 78             /*//异常
 79             int i=9/0;
 80             //....
 81 */            transaction.commit();
 82             
 83             
 84         }catch (Exception e) {
 85             if(transaction!=null) {
 86                 transaction.rollback();
 87             }
 88             
 89             throw new RuntimeException(e.getMessage());
 90         } finally {
 91             //关闭session
 92             if(session!=null&&session.isOpen()) {
 93                 session.close();
 94             }
 95             
 96         }
 97         
 98         
 99     }
100     /**
101      * 添加用户
102      */
103     public static void addEmployee() {
104         //使用hibernate完成crud操作
105         //现在不使用service,直接测试
106         //1.创建Configuration,该对象用于读取hibernate.cfg.xml并完成初始化
107         Configuration configuration = new Configuration().configure();
108         //2.创建SessionFactory【这是一个会话工厂,是一个重量级的对象】
109         SessionFactory sessionFactory = configuration.buildSessionFactory();
110         //3.创建Session,相当于jdbc中的Connection
111         Session  session = sessionFactory.openSession();
112         //4.对于hibernate,要求在进行增加,删除,修改的时候使用事物提交
113         Transaction transaction = session.beginTransaction();
114         
115         try {
116             
117             //添加一个雇员
118             Employee employee = new Employee();
119             employee.setName("zhangsan");
120             employee.setEmail("zhangsan@126.com");
121             employee.setHiredate(new Date());
122             
123             //保存,把对象保存到数据库
124             session.save(employee);//相当于insert into....[被hibernate封装]
125             transaction.commit();
126             session.close();
127             
128         }catch (Exception e) {
129             if(transaction!=null) {
130                 transaction.rollback();
131             }
132             
133             throw new RuntimeException(e.getMessage());
134         } finally {
135             //关闭session
136             if(session!=null&&session.isOpen()) {
137                 session.close();
138             }
139             
140         }
141     }
142 
143 }
原文地址:https://www.cnblogs.com/lihuibin/p/8168260.html