1.

 package mypack;
public class Monkey{ private Long id;
private String name;
private int count;
private int version; public Monkey() {} public Long getId() {
return this.id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
} public int getCount() {
return this.count;
} public void setCount(int count) {
this.count = count;
} public int getVersion() {
return this.version;
} public void setVersion(int version) {
this.version = version;
}
}

2.

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping > <class name="mypack.Monkey" table="MONKEYS" >
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id> <version name="version" column="VERSION" /> <property name="name" type="string" column="NAME" /> <property name="count" type="int" column="COUNT" /> </class>
</hibernate-mapping>

3.

 package mypack;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration; public class HibernateUtil {
private static SessionFactory sessionFactory; static{
try {
sessionFactory=new Configuration()
.configure()
.buildSessionFactory();
}catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
} public static Session getCurrentSession(){
return sessionFactory.getCurrentSession();
} }

4.

 package mypack;
public class MonkeyDAO{
public Monkey getById(long id){
return (Monkey)HibernateUtil.getCurrentSession()
.get(Monkey.class,new Long(id));
} public void update(Monkey monkey){
HibernateUtil.getCurrentSession().saveOrUpdate(monkey);
}
}

5.

 package mypack;
import org.hibernate.Session; public class MonkeyDAO2{
public Monkey getById(long id,Session session){
return (Monkey)session.get(Monkey.class,new Long(id));
} public void update(Monkey monkey,Session session){
session.saveOrUpdate(monkey);
}
}

6.

 package mypack;
public class BusinessService{
private MonkeyDAO md=new MonkeyDAO(); public void vote(long monkeyId){
try {
//声明开始事务
HibernateUtil.getCurrentSession().beginTransaction(); Monkey monkey=md.getById(monkeyId);
monkey.setCount(monkey.getCount()+1); //提交事务
HibernateUtil.getCurrentSession().getTransaction().commit(); }catch (RuntimeException e) {
try{
//撤销事务
HibernateUtil.getCurrentSession().getTransaction().rollback();
}catch(RuntimeException ex){
ex.printStackTrace();
}
throw e;
} } public static void main(String args[]) {
new BusinessService().vote(1);
}
}

7.

 package mypack;
import java.io.*;
import java.util.Scanner; public class BusinessService1{
private MonkeyDAO md=new MonkeyDAO(); public void vote()throws Exception{
System.out.println("请输入候选者的ID:");
//等待用户输入候选者的ID,此操作可能会化去很长时间,取决于用户的思考时间
long monkeyId=new Scanner(System.in).nextLong(); Monkey monkey=getMonkey(monkeyId); System.out.println("候选者的当前票数为:"+monkey.getCount()); System.out.println("您确信要投票吗(Y/N):");
//等待用户确认是否投票,此操作可能会花去很长时间,取决于用户的思考时间
String flag=new Scanner(System.in).next();
if(flag.equals("N"))return; monkey.setCount(monkey.getCount()+1);
updateMonkey(monkey); System.out.println("投票成功,候选者的当前票数为:"+monkey.getCount());
} public Monkey getMonkey(long monkeyId){
try{
//创建一个Session对象,声明开始查询候选者事务
HibernateUtil.getCurrentSession().beginTransaction(); Monkey monkey=md.getById(monkeyId); //提交事务,在Session与本地线程绑定的方式下,会自动关闭Session对象
HibernateUtil.getCurrentSession().getTransaction().commit(); return monkey;
}catch (RuntimeException e) {
try{
//撤销事务
HibernateUtil.getCurrentSession().getTransaction().rollback();
}catch(RuntimeException ex){
ex.printStackTrace();
}
throw e;
} } public void updateMonkey(Monkey monkey){
try{
//创建一个Session对象,声明开始修改票数事务
HibernateUtil.getCurrentSession().beginTransaction(); md.update(monkey); //提交事务,在Session与本地线程绑定的方式下,会自动关闭Session对象
HibernateUtil.getCurrentSession().getTransaction().commit(); }catch (RuntimeException e) {
try{
//撤销事务
HibernateUtil.getCurrentSession().getTransaction().rollback();
}catch(RuntimeException ex){
ex.printStackTrace();
}
throw e;
}
} public static void main(String args[]) throws Exception {
new BusinessService1().vote();
}
}

8.

 package mypack;
import java.io.*;
import java.util.Scanner;
import org.hibernate.*; public class BusinessService2{
private MonkeyDAO2 md=new MonkeyDAO2(); public void vote()throws Exception{
Session session=null;
try{
System.out.println("请输入候选者的ID:");
//等待用户输入候选者的ID,此操作可能会化去很长时间,取决于用户的思考时间
long monkeyId=new Scanner(System.in).nextLong(); //创建一个Session对象,由程序自主管理Session对象的生命周期
session=HibernateUtil.getSessionFactory().openSession();
//设为手工清理缓存模式
session.setFlushMode(FlushMode.MANUAL); //声明开始查询候选者事务
session.beginTransaction();
Monkey monkey=md.getById(monkeyId,session);
//提交查询候选者事务,释放Session占用的数据库连接
session.getTransaction().commit(); System.out.println("候选者的当前票数为:"+monkey.getCount()); System.out.println("您确信要投票吗(Y/N):");
//等待用户确认是否投票,此操作可能会花去很长时间,取决于用户的思考时间
String flag=new Scanner(System.in).next();
if(flag.equals("N"))return; monkey.setCount(monkey.getCount()+1); //声明开始修改票数事务,为Session重新分配数据库连接
session.beginTransaction();
md.update(monkey,session); //清理缓存
session.flush(); //提交修改票数事务
session.getTransaction().commit(); System.out.println("投票成功,候选者的当前票数为:"+monkey.getCount());
}catch (RuntimeException e) {
try{
//撤销事务
session.getTransaction().rollback();
}catch(RuntimeException ex){
ex.printStackTrace();
}
throw e;
}finally{
session.close();
}
} public static void main(String args[]) throws Exception {
new BusinessService2().vote();
}
}

9.

 /** 运行此程序时,
必须把hibernate.cfg.xml文件中的current_session_context_class属性设为managed
*/ package mypack;
import java.io.*;
import java.util.Scanner;
import org.hibernate.classic.Session;
import org.hibernate.context.ManagedSessionContext;
import org.hibernate.FlushMode; public class BusinessService3{
private MonkeyDAO md=new MonkeyDAO(); public void vote()throws Exception{
Session session=null;
try{
System.out.println("请输入候选者的ID:");
//等待用户输入候选者的ID,此操作可能会化去很长时间,取决于用户的思考时间
long monkeyId=new Scanner(System.in).nextLong(); //创建一个Session对象,由程序自主管理Session对象的生命周期
session=HibernateUtil.getSessionFactory().openSession();
//设为手工清理缓存模式
session.setFlushMode(FlushMode.MANUAL);
ManagedSessionContext.bind(session); //声明开始查询候选者事务
session.beginTransaction();
Monkey monkey=md.getById(monkeyId); ManagedSessionContext.unbind(HibernateUtil.getSessionFactory()); //提交查询候选者事务,释放Session占用的数据库连接
session.getTransaction().commit();
System.out.println("候选者的当前票数为:"+monkey.getCount()); System.out.println("您确信要投票吗(Y/N):");
//等待用户确认是否投票,此操作可能会花去很长时间,取决于用户的思考时间
String flag=new Scanner(System.in).next();
if(flag.equals("N"))return; monkey.setCount(monkey.getCount()+1); ManagedSessionContext.bind(session); //声明开始修改票数事务,为Session重新分配数据库连接
session.beginTransaction();
md.update(monkey); ManagedSessionContext.unbind(HibernateUtil.getSessionFactory()); //清理缓存
session.flush(); //提交修改票数事务
session.getTransaction().commit(); System.out.println("投票成功,候选者的当前票数为:"+monkey.getCount());
}catch (RuntimeException e) {
try{
//撤销事务
session.getTransaction().rollback();
}catch(RuntimeException ex){
ex.printStackTrace();
}
throw e;
}finally{
session.close();
}
} public static void main(String args[]) throws Exception {
new BusinessService3().vote();
}
}

10.

 <?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/sampledb
</property>
<property name="connection.username">
root
</property>
<property name="connection.password">
1234
</property>
<property name="show_sql">true</property>
<!--
<property name="current_session_context_class">managed</property>
-->
<property name="current_session_context_class">thread</property>
<mapping resource="mypack/Monkey.hbm.xml" />
</session-factory>
</hibernate-configuration>

11.

12.

13.

:Hibernate逍遥游记-第16管理session和实现对话的更多相关文章

  1. Hibernate逍遥游记-第15章处理并发问题-003乐观锁

    1. 2. drop database if exists SAMPLEDB; create database SAMPLEDB; use SAMPLEDB; drop table if exists ...

  2. Hibernate逍遥游记-第15章处理并发问题-002悲观锁

    1. 2. hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.connection.driver_class=com.mys ...

  3. Hibernate逍遥游记-第13章 映射实体关联关系-006双向多对多(分解为一对多)

    1. 2. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate ...

  4. Hibernate逍遥游记-第13章 映射实体关联关系-005双向多对多(使用组件类集合\<composite-element>\)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  5. Hibernate逍遥游记-第13章 映射实体关联关系-004双向多对多(inverse="true")

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  6. Hibernate逍遥游记-第13章 映射实体关联关系-003单向多对多

    0. 1. drop database if exists SAMPLEDB; create database SAMPLEDB; use SAMPLEDB; create table MONKEYS ...

  7. Hibernate逍遥游记-第13章 映射实体关联关系-002用主键映射一对一(<one-to-one constrained="true">、<generator class="foreign">)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  8. Hibernate逍遥游记-第13章 映射实体关联关系-001用外键映射一对一(<many-to-one unique="true">、<one-to-one>)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  9. Hibernate逍遥游记-第12章 映射值类型集合-005对集合排序Map(<order-by>\<sort>)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

随机推荐

  1. 使用Telerik的登陆模板实现DoubanFm的登陆(WP7)

    Telerik的控件很强大.我们直接使用其登陆模板. 在装过Telerik WP版后,就可以在VS里非常方便的添加页面了. 我们选择 Sign In Form 其XAML不是很长,直接贴出来 < ...

  2. Keil uVision4 代码编辑器中文字符乱码问题

    MDK-ARM 使用中一直有个很纠结的问题,中文字符支持不好. 比如写代码注释,使用中文删除字符就会只删除一半问题.复制粘贴代码中间有中文就会出现乱码问题. 想过换IAR,新学个IDE也麻烦,上面的问 ...

  3. Oracle物理的体系结构

    体系结构图的学习: 老余服装店的故事 结构图: SQL查询语句 SGA 共享池shared pool 数据缓存区Buffer cache PGA 进程 SQL更新语句 SGA: 日志缓存区 日志文件 ...

  4. static方法不能直接访问类内的非static变量和不能调用this,super语句分析

    大家都知道在static方法中,不能访问类内非static成员变量和方法.可是原因是什么呢? 这首先要从static方法的特性说起.static方法,即类的静态成员经常被称为"成员变量&qu ...

  5. 【Nhibernate】入门 踩雷篇

    总结(喜欢写在前面,记性不好老忘记解决问题时的思路): 使用框架一般不会完整的看文档,直接上来就搞,踩雷是必须的,重要的是遇到雷的时候要快速变换思路,是不是姿势不对(文件位置不对) 提高解决问题的速度 ...

  6. C#基础原理拾遗——面试都爱问的委托和事件(纠正)

    这篇博客是我昨天写的,文中的观点有些问题,后经过网友留言和个人学习发现错误,原文还是保留,更改补在后面,不怕贻笑大方,唯恐误人子弟.不知道还能不能放在首页,让被误导的同学再被反误导一次. 一.原文 几 ...

  7. Android crop image size

    private void performCrop() { try { //call the standard crop action intent (the user device may not s ...

  8. [algothrim]URL相似度计算的思考

    http://www.spongeliu.com/399.html http://in.sdo.com/?p=865

  9. linux文件系统创建文件的过程

    创建一个文件最主要的步骤就是: 1.为文件创建一个文件目录项. 2.为文件创建一个inode结构并分配inode号,将inode编号与文件名映射关系保存在1中分配的文件目录项中. 3.将1中创建的文件 ...

  10. 阿里云CentOS6.3 安装MongoDB教程

    安装说明 系统环境:Centos-6.3安装软件:mongodb-linux-x86_64-2.2.2.tgz下载地址:http://www.mongodb.org/downloads安装机器:192 ...