:Hibernate逍遥游记-第16管理session和实现对话

1.

 1 package mypack;
 2 public class Monkey{
 3 
 4     private Long id;
 5     private String name;
 6     private int count;
 7     private int version;
 8 
 9     public Monkey() {}
10 
11     public Long getId() {
12         return this.id;
13     }
14 
15     public void setId(Long id) {
16         this.id = id;
17     }
18 
19     public String getName() {
20         return this.name;
21     }
22 
23     public void setName(String name) {
24         this.name = name;
25     }
26 
27     public int getCount() {
28         return this.count;
29     }
30 
31     public void setCount(int count) {
32         this.count = count;
33     }
34 
35     public int getVersion() {
36         return this.version;
37     }
38 
39     public void setVersion(int version) {
40         this.version = version;
41     }
42 }

 

2.

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping
 3 PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping >
 6 
 7   <class name="mypack.Monkey" table="MONKEYS" >
 8     <id name="id" type="long" column="ID">
 9       <generator class="increment"/>
10     </id>
11 
12     <version name="version" column="VERSION" />
13     
14     <property name="name" type="string" column="NAME" />
15  
16     <property name="count" type="int" column="COUNT" />
17      
18   </class>
19 </hibernate-mapping>

 

3.

 1 package mypack;
 2 import org.hibernate.SessionFactory;
 3 import org.hibernate.Session;
 4 import org.hibernate.cfg.Configuration;
 5 
 6 public class HibernateUtil {
 7   private static SessionFactory sessionFactory;
 8 
 9   static{
10     try {
11       sessionFactory=new Configuration()
12                                       .configure()
13                                       .buildSessionFactory();
14     }catch (Throwable ex) {
15       throw new ExceptionInInitializerError(ex);
16     }
17    }
18 
19    public static SessionFactory getSessionFactory() {
20      return sessionFactory;
21    }
22 
23    public static Session getCurrentSession(){
24      return sessionFactory.getCurrentSession();
25    }
26    
27 }

 

4.

 1 package mypack;
 2 public class MonkeyDAO{
 3   public Monkey getById(long id){
 4     return (Monkey)HibernateUtil.getCurrentSession()
 5                         .get(Monkey.class,new Long(id));
 6   }
 7 
 8   public void update(Monkey monkey){
 9     HibernateUtil.getCurrentSession().saveOrUpdate(monkey);
10   }
11 }

 

5.

 1 package mypack;
 2 import org.hibernate.Session;
 3 
 4 public class MonkeyDAO2{
 5   public Monkey getById(long id,Session session){
 6     return (Monkey)session.get(Monkey.class,new Long(id));
 7   }
 8 
 9   public void update(Monkey monkey,Session session){
10     session.saveOrUpdate(monkey);
11   }
12 }

 

6.

 1 package mypack;
 2 public class BusinessService{
 3   private MonkeyDAO md=new MonkeyDAO();
 4 
 5   public void vote(long monkeyId){
 6     try {
 7       //声明开始事务
 8       HibernateUtil.getCurrentSession().beginTransaction();
 9  
10       Monkey monkey=md.getById(monkeyId);
11       monkey.setCount(monkey.getCount()+1);
12  
13       //提交事务      
14       HibernateUtil.getCurrentSession().getTransaction().commit();
15  
16     }catch (RuntimeException e) {
17       try{
18          //撤销事务
19          HibernateUtil.getCurrentSession().getTransaction().rollback();
20       }catch(RuntimeException ex){
21          ex.printStackTrace(); 
22       }
23       throw e;
24     }
25 
26   }
27 
28   public static void main(String args[]) {
29     new BusinessService().vote(1);    
30   }
31 }

:Hibernate逍遥游记-第16管理session和实现对话_第1张图片

7.

 1 package mypack;
 2 import java.io.*;
 3 import java.util.Scanner;
 4 
 5 public class BusinessService1{
 6   private MonkeyDAO md=new MonkeyDAO();
 7 
 8   public void vote()throws Exception{
 9     System.out.println("请输入候选者的ID:");
10     //等待用户输入候选者的ID,此操作可能会化去很长时间,取决于用户的思考时间
11     long monkeyId=new Scanner(System.in).nextLong(); 
12  
13     Monkey monkey=getMonkey(monkeyId);
14 
15     System.out.println("候选者的当前票数为:"+monkey.getCount());
16     
17     System.out.println("您确信要投票吗(Y/N):");
18     //等待用户确认是否投票,此操作可能会花去很长时间,取决于用户的思考时间
19     String flag=new Scanner(System.in).next(); 
20     if(flag.equals("N"))return;
21 
22     monkey.setCount(monkey.getCount()+1);
23     updateMonkey(monkey);
24 
25     System.out.println("投票成功,候选者的当前票数为:"+monkey.getCount());
26   }
27 
28 
29   public Monkey getMonkey(long monkeyId){
30     try{
31       //创建一个Session对象,声明开始查询候选者事务
32       HibernateUtil.getCurrentSession().beginTransaction();
33 
34       Monkey monkey=md.getById(monkeyId);
35     
36       //提交事务,在Session与本地线程绑定的方式下,会自动关闭Session对象      
37       HibernateUtil.getCurrentSession().getTransaction().commit();
38 
39       return monkey;
40     }catch (RuntimeException e) {
41       try{
42          //撤销事务
43          HibernateUtil.getCurrentSession().getTransaction().rollback();
44       }catch(RuntimeException ex){
45          ex.printStackTrace(); 
46       }
47       throw e;
48     }
49 
50   }
51 
52   public void updateMonkey(Monkey monkey){
53     try{
54       //创建一个Session对象,声明开始修改票数事务
55       HibernateUtil.getCurrentSession().beginTransaction();
56 
57       md.update(monkey);
58     
59       //提交事务,在Session与本地线程绑定的方式下,会自动关闭Session对象      
60       HibernateUtil.getCurrentSession().getTransaction().commit();
61 
62     }catch (RuntimeException e) {
63       try{
64          //撤销事务
65          HibernateUtil.getCurrentSession().getTransaction().rollback();
66       }catch(RuntimeException ex){
67          ex.printStackTrace(); 
68       }
69       throw e;
70     }
71   }
72   
73   public static void main(String args[]) throws Exception {
74     new BusinessService1().vote();    
75   }
76 }

 

8.

 1 package mypack;
 2 import java.io.*;
 3 import java.util.Scanner;
 4 import org.hibernate.*;
 5 
 6 public class BusinessService2{
 7   private MonkeyDAO2 md=new MonkeyDAO2();
 8 
 9   public void vote()throws Exception{
10     Session session=null;
11     try{
12       System.out.println("请输入候选者的ID:");
13       //等待用户输入候选者的ID,此操作可能会化去很长时间,取决于用户的思考时间
14       long monkeyId=new Scanner(System.in).nextLong(); 
15 
16       //创建一个Session对象,由程序自主管理Session对象的生命周期
17       session=HibernateUtil.getSessionFactory().openSession();
18       //设为手工清理缓存模式
19       session.setFlushMode(FlushMode.MANUAL);
20 
21       //声明开始查询候选者事务
22       session.beginTransaction();
23       Monkey monkey=md.getById(monkeyId,session);
24       //提交查询候选者事务,释放Session占用的数据库连接
25       session.getTransaction().commit();
26 
27       System.out.println("候选者的当前票数为:"+monkey.getCount());
28 
29       System.out.println("您确信要投票吗(Y/N):");
30       //等待用户确认是否投票,此操作可能会花去很长时间,取决于用户的思考时间
31       String flag=new Scanner(System.in).next(); 
32       if(flag.equals("N"))return;
33 
34       monkey.setCount(monkey.getCount()+1);
35 
36       //声明开始修改票数事务,为Session重新分配数据库连接
37       session.beginTransaction();
38       md.update(monkey,session); 
39     
40       //清理缓存
41       session.flush();
42 
43       //提交修改票数事务      
44       session.getTransaction().commit();
45 
46       System.out.println("投票成功,候选者的当前票数为:"+monkey.getCount());
47     }catch (RuntimeException e) {
48       try{
49          //撤销事务
50          session.getTransaction().rollback();
51       }catch(RuntimeException ex){
52          ex.printStackTrace(); 
53       }
54       throw e;
55     }finally{
56       session.close();
57     }
58   }
59 
60   public static void main(String args[]) throws Exception {
61     new BusinessService2().vote();    
62   }
63 }

 

9.

 1 /** 运行此程序时,
 2 必须把hibernate.cfg.xml文件中的current_session_context_class属性设为managed
 3 */
 4 
 5 package mypack;
 6 import java.io.*;
 7 import java.util.Scanner;
 8 import org.hibernate.classic.Session;
 9 import org.hibernate.context.ManagedSessionContext;
10 import org.hibernate.FlushMode;
11 
12 public class BusinessService3{
13   private MonkeyDAO md=new MonkeyDAO();
14 
15   public void vote()throws Exception{
16     Session session=null;
17     try{
18       System.out.println("请输入候选者的ID:");
19       //等待用户输入候选者的ID,此操作可能会化去很长时间,取决于用户的思考时间
20       long monkeyId=new Scanner(System.in).nextLong(); 
21 
22       //创建一个Session对象,由程序自主管理Session对象的生命周期
23       session=HibernateUtil.getSessionFactory().openSession();
24       //设为手工清理缓存模式
25       session.setFlushMode(FlushMode.MANUAL);
26       ManagedSessionContext.bind(session);
27 
28       //声明开始查询候选者事务
29       session.beginTransaction();
30       Monkey monkey=md.getById(monkeyId);
31       
32       ManagedSessionContext.unbind(HibernateUtil.getSessionFactory());
33 
34       //提交查询候选者事务,释放Session占用的数据库连接
35       session.getTransaction().commit();
36       System.out.println("候选者的当前票数为:"+monkey.getCount());
37       
38       System.out.println("您确信要投票吗(Y/N):");
39       //等待用户确认是否投票,此操作可能会花去很长时间,取决于用户的思考时间
40       String flag=new Scanner(System.in).next(); 
41       if(flag.equals("N"))return;
42 
43       monkey.setCount(monkey.getCount()+1);
44 
45       ManagedSessionContext.bind(session);
46 
47       //声明开始修改票数事务,为Session重新分配数据库连接
48       session.beginTransaction();
49       md.update(monkey); 
50     
51       ManagedSessionContext.unbind(HibernateUtil.getSessionFactory());
52 
53       //清理缓存
54       session.flush();
55 
56       //提交修改票数事务      
57       session.getTransaction().commit();
58 
59       System.out.println("投票成功,候选者的当前票数为:"+monkey.getCount());
60     }catch (RuntimeException e) {
61       try{
62          //撤销事务
63          session.getTransaction().rollback();
64       }catch(RuntimeException ex){
65          ex.printStackTrace(); 
66       }
67       throw e;
68     }finally{
69       session.close();
70     }
71   }
72 
73   public static void main(String args[]) throws Exception {
74     new BusinessService3().vote();    
75   }
76 }

10.

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <!DOCTYPE hibernate-configuration
 3  PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
 4  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <property name="dialect">
 8             org.hibernate.dialect.MySQLDialect
 9         </property>
10         <property name="connection.driver_class">
11             com.mysql.jdbc.Driver
12         </property>
13         <property name="connection.url">
14             jdbc:mysql://localhost:3306/sampledb
15         </property>
16         <property name="connection.username">
17             root
18         </property>
19         <property name="connection.password">
20             1234
21         </property>
22         <property name="show_sql">true</property>
23         <!--
24 <property name="current_session_context_class">managed</property>
25 -->
26         <property name="current_session_context_class">thread</property>
27         <mapping resource="mypack/Monkey.hbm.xml" />
28     </session-factory>
29 </hibernate-configuration>

 

11.

 

12.

 

13.

:Hibernate逍遥游记-第16管理session和实现对话_第2张图片:Hibernate逍遥游记-第16管理session和实现对话_第3张图片:Hibernate逍遥游记-第16管理session和实现对话_第4张图片

你可能感兴趣的:(:Hibernate逍遥游记-第16管理session和实现对话)