一,为接下来的测试添加java实体类和建立数据库映射表account:
1, 项目目录:
2、用户实体类:Account:
package com.hibtest.entity;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;
/*Account账户类的测试*/
public class AccountTest {
@Test
public void createAccountDatabaseMapping()
{
//加载Hibernate的配置文件
Configuration config = new Configuration().configure();
//生成服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//生成sessionFactory
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//获得SchemaExport
SchemaExport schemaExport = new SchemaExport(config);
//生成数据库表
schemaExport.create(true, true);
}
}
3,hinernate.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">
<!-- old: http://hibernate.sourceforge.net/hibernate-configuration-3.6.dtd -->
<!-- new: http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd -->
<!-- : http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd -->
<hibernate-configuration>
<session-factory>
<!-- 显示sql语句 -->
<property name="show_sql">true</property>
<property name="myeclipse.connection.profile">bookshop</property>
<!-- <property name="connection.url">
jdbc:mysql://localhost:3306/bookshop
jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=UTF-8
</property> -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8</property>
<property name="connection.username">root</property>
<property name="connection.password">910214</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.current_session_context_class">thread</property>
<!-- 将实体类映射到数据库 -->
<!--
<mapping class="oto_fk.Students"/>
<mapping class="oto_fk.IdCard"/>
-->
<!-- 添加Users的数据库映射 -->
<!--
<mapping class="com.hibtest.entity.Users"/>
-->
<!-- <mapping class="com.hibtest.entity.IdCard"/>-->
<!-- 添加数据库映射 -->
<mapping class="com.hibtest.entity.Account"/>
</session-factory>
</hibernate-configuration>
4, 测试文件编写:生成数据库表account:
package com.hibtest.entity;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;
/*Account账户类的测试*/
public class AccountTest {
@Test
public void createAccountDatabaseMapping()
{
//加载Hibernate的配置文件
Configuration config = new Configuration().configure();
//生成服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//生成sessionFactory
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//获得SchemaExport
SchemaExport schemaExport = new SchemaExport(config);
//生成数据库表
schemaExport.create(true, true);
}
}
实施生成数据库表状态截图:
数据库对应生成的表:
向account表添加测试数据:
//向用户表Account中添加两条测试记录
@Test
public void insertItoAccount()
{
//加载Hibernate的配置文件
Configuration config = new Configuration().configure();
//生成服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//生成sessionFactory
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//生成session对象
Session session = sessionFactory.getCurrentSession();
//获得事务并开启
Transaction tx = session.beginTransaction();
try{
//获得两个Account对象
Account acc1 = new Account();
Account acc2 = new Account();
acc1.setAccountNo("00000001");
acc1.setBalance(1000);
acc2.setAccountNo("00000002");
acc2.setBalance(1000);
//保存对象
session.save(acc1);
session.save(acc2);
//提交事务
tx.commit();
}
catch(HibernateException ex)
{
//打印异常堆栈
ex.printStackTrace();
//事务回滚
tx.rollback();
}
}
模拟取款业务:TransactionA.java:
package com.hibtest.entity;
import java.util.TimerTask;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class TransactionA extends TimerTask {
//模拟取款操作
@Override
public void run() {
//加载Hibernate的配置文件
Configuration config = new Configuration().configure();
//生成服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//生成sessionFactory
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//生成session对象
Session session = sessionFactory.getCurrentSession();
//获得事务并开启
Transaction tx = session.beginTransaction();
try{
System.out.println("模拟取款任务开始: ");
//创建HQL语句
String hql = "from Account where Id=1";
//创建一个Query对象
Query query = session.createQuery(hql);
//设置访问创建的对象a时的锁模式
query.setLockMode("a", LockMode.UPGRADE_NOWAIT);//LockMode.UPGRADE_NOWAIT表示执行该select语句不成立则获得悲观锁
Account acc = (Account)query.uniqueResult();
//打印查询信息
System.out.println("查询到的账户余额为: "+acc.getBalance());
//将账户的余额减少100元之后
acc.setBalance(acc.getBalance() - 100);
System.out.println("取款100元之后: "+acc.getBalance());
//修改执行对象
session.update(acc);
//提交事务
tx.commit();
}
catch(HibernateException ex)
{
//打印异常堆栈
ex.printStackTrace();
//事务回滚
tx.rollback();
}
}
}
模拟汇款任务TransactionB.java:
package com.hibtest.entity;
import java.util.TimerTask;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class TransactionB extends TimerTask {
//模拟取款操作
@Override
public void run() {
//加载Hibernate的配置文件
Configuration config = new Configuration().configure();
//生成服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//生成sessionFactory
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//生成session对象
Session session = sessionFactory.getCurrentSession();
//获得事务并开启
Transaction tx = session.beginTransaction();
try{
System.out.println("模拟转账任务开始: ");
//创建HQL语句
String hql = "from Account where Id=1";
//创建一个Query对象
Query query = session.createQuery(hql);
//设置访问创建的对象时的锁模式
query.setLockMode("a", LockMode.UPGRADE_NOWAIT);//LockMode.UPGRADE_NOWAIT表示执行该select语句不成立则获得悲观锁
Account acc = (Account)query.uniqueResult();
query.setLockMode("acc", LockMode.UPGRADE_NOWAIT);
//打印查询信息
System.out.println("查询到的存款账户余额为: "+acc.getBalance());
//将账户B的余额增加100元之后
acc.setBalance(acc.getBalance() + 100);
System.out.println("汇款100元之后: "+acc.getBalance());
//修改执行对象
session.update(acc);
//提交事务
tx.commit();
}
catch(HibernateException ex)
{
//打印异常堆栈
ex.printStackTrace();
//事务回滚
tx.rollback();
}
}
}
实施取款汇款业务:
package com.hibtest.entity;
import java.util.Timer;
public class testTransactionAB {
/**
* @param args
*/
public static void main(String[] args) {
new testTransactionAB().testGetSet();
}
public void testGetSet()
{
//悲观锁,分别通过定时器启动事务A和事务B
Timer timer1 = new Timer();
//立即启动事务A的线程
timer1.schedule(new TransactionA(),0);
Timer timer2 = new Timer();
//立即启动事务B的线程
timer2.schedule(new TransactionB(),0);
}
}
后台打印的log:
模拟取款任务开始:
模拟转账任务开始:
Hibernate:
select
account0_.id as id0_,
account0_.accountNo as accountNo0_,
account0_.balance as balance0_
from
Account account0_
where
Id=1
Hibernate:
select
account0_.id as id0_,
account0_.accountNo as accountNo0_,
account0_.balance as balance0_
from
Account account0_
where
Id=1
查询到的账户余额为: 1000
取款100元之后: 900
查询到的存款账户余额为: 1000
汇款100元之后: 1100
Hibernate:
update
Account
set
accountNo=?,
balance=?
where
id=?
Hibernate:
update
Account
set
accountNo=?,
balance=?
where
id = ?