欢迎访问我的个人网站==》 jiashubing.cn

hibernate案例 测试代码

 

测试staff数据表连接到maeclipse

在staff中插入一行

 1 package com.hibernate.test;
 2 
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.Transaction;
 6 import org.hibernate.cfg.Configuration;
 7 
 8 import com.hibernate.DAO.Staff;
 9 
10 
11 public class StaffTest
12 {
13     public void save()
14     {
15         Configuration conf = new Configuration();
16         //无参数,默认加载Hibenate.cfg.xml,也可以闯入其他配置文件名,进行加载
17         
18         conf.configure();
19         /*如果Hibernate.cfg.xml中没有配置某些属性,可以通过conf.setProperty(propertyName, value);来配置 
20         如: conf.setProperty("'hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
21         */
22         
23         SessionFactory factory = conf.buildSessionFactory();
24         //用于构造Session实力的工厂对象
25         
26         Session session = factory.openSession();
27         //构造Session
28         
29         Transaction tran = session.beginTransaction();
30         //通过Session实例开启事务,得到事务对象
31         
32         //创建staff实体类对象
33         try{
34             Staff staff = new Staff();
35             staff.setId("8888888");
36             staff.setName("888888");
37             staff.setPassword("888888");
38             
39             //使用session实例的save()方法,传入实体类对象,将staff对象持久化
40             session.save(staff);
41             tran.commit();
42         }catch(Exception e){
43             tran.rollback();
44         }finally{
45             //关闭session
46             session.close();
47         }
48     }
49     public static void main(String[] args)
50     {
51         StaffTest test = new StaffTest();
52         test.save();
53     }
54 }

 

posted @ 2014-04-22 11:39  贾树丙  阅读(298)  评论(0编辑  收藏  举报