我接触的个人感觉很简单,和超哥聊完发现。在hibernate4.0.getCurrentSession()这种方法几乎不常用,就是一个hibernate映射表的一个小例子吧
step:
1、建工程
2、导入需要的jar包
3、创建映射实体类
4、创建配置hibernate的配置文件hibernate.cfg.xml,即配置hibernate 模板
5、配置 hibernate 的基本属性 二级缓存相关
6、创建Spring的bean配置文件,配置到sessionfactorybean实例,创建测试类,运行、完成表映射
8、写接口实现类,继续配置bean
直接上代码了:
实体类:
package com.spring.bean.entity; public class Account { private Integer id; String username; private int balance; public Integer getId() { return id; } void setId(Integer id) { this.id = String getUsername() { username; } setUsername(String username) { this.username = getBalance() { balance; } void setBalance( balance) { this.balance = balance; } }
Book { String bookName; String isbn; price; stock; String getBookName() { bookName; } setBookName(String bookName) { this.bookName = String getIsbn() { isbn; } setIsbn(String isbn) { this.isbn = getPrice() { price; } void setPrice( price) { this.price = getStock() { stock; } void setStock( stock) { this.stock = stock; } }
hibernate.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"> <hibernate-configuration> session-factory> property name="hibernate.dialect">org.hibernate.dialect.MysqL5InnoDBDialect</property="hibernate.show_sql">true="hibernate.format_sql"="hibernate.hbm2ddl.auto">update>
映射生成的*.hbm,xml
xml version="1.0"DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"<!-- Generated 2017-1-25 19:42:09 by Hibernate Tools 3.5.0.Final --> hibernate-mappingclass ="com.spring.bean.entity.Account" table="Account"id ="id" type="java.lang.Integer"> column ="ID" /> generator ="native" /> id="username"="java.lang.String"="username" ="balance"="int"="balance" >
="com.spring.bean.entity.Book"="Book"="bookName"="bookName" ="isbn"="isbn" ="price"="price" ="stock"="stock" >
接口不上了只上实现类(bookshaodao)
com.spring.bean.respistory; import org.hibernate.Session; org.hibernate.SessionFactory; org.springframework.beans.factory.annotation.Autowired; org.springframework.stereotype.Repository; @Repository("bookShopDao") class BookShopDaoImpl implements BookShopDao { @Autowired SessionFactory session; Session getCurrentSession(){ session.getCurrentSession(); } @Override findBookPriceByIsbn(String isbn) { String hsql = "SELECT b.price FROM Book b WHERE b.isbn = ?"; int price = (int) getCurrentSession().createQuery(hsql).setString(0,isbn).uniqueResult(); price; } @Override updateBookStock(String isbn) { //检查书的库存是否足够,若不够,则抛出异常 String hsql2 = "SELECT b.stock FROM Book b WHERE b.isbn = ?"int stock = (int) getCurrentSession().createQuery(hsql2).setString(0if(stock == 0){ throw new BookStockException("库存不足!"); } String hsql = "UPDATE Book b SET b.stock = b.stock -1 WHERE b.isbn = ?"; getCurrentSession().createQuery(hsql).setString(0void updateUserAccount(String username,验证余额是否足够,若不足,则抛出异常 String hsql2 = "SELECT a.balance FROM Account a WHERE a.username = ?"int balance = (if(balance < price){ new UserAccountException("余额不足!"); } String hsql = "UPDATE Account a SET a.balance = a.balance - ? WHERE a.username = ?"; getCurrentSession().createQuery(hsql).setInteger(0,price).setString(1beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd" 自动扫描需要的包 --> context:component-scan base-package="com.spring.bean"></context:component-scan 加载外部资源文件 context:property-placeholder location="classpath:db.properties"/> 配置MysqL bean ="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" value="${jdbc.user}"="password"="${jdbc.password}"="url"="${jdbc.jdbcUrl}"="driverClassName"="${jdbc.driverClass}"bean hibernate的sessionFactory实例 ="sessionfactorybean"="org.springframework.orm.hibernate4.LocalSessionfactorybean" 配置数据源 --> ref="dataSource" 配置文件名称及位置 --><!-- 也可以通过hibernateProperties配置 <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> ="hibernateProperties"props> prop keyprop 配置映射文件名称和位置 ="mappingLocations"="classpath:com/spring/bean/entity/*.hbm.xml" 配置声明式事务管理器 ="transactionManager"="org.springframework.orm.hibernate4.HibernateTransactionManager"="sessionFactory"="sessionfactorybean" 配置事物属性 tx:advice ="taAdvice" transaction-manager="transactionManager"tx:attributestx:method ="get*" read-only="true"="purchase" propagation="REQUIRES_NEW"="*"tx:advice 配置事物切点 aop:configaop:pointcut expression="execution(* com.spring.bean.services.*.*(..))" id="pointcut"aop:advisor advice-ref pointcut-ref> beans>
在实现类中有几个细节吧
1、sql必须写成这样的如:
SELECT b.price FROM Book b WHERE b.isbn = ?即表明必须与生成的hbm.xml中的table中的名字一致
<class name="com.spring.bean.entity.Book" table="Book">
要是写成不一致sql会报错:
org.hibernate.hql.internal.ast.QuerySyntaxException: book is not mapped [SELECT price FROM book WHERE isbn = ?]
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)
at org.hibernate.hql.internal.ast.HqlsqlWalker.createFromElement(HqlsqlWalker.java:324)
at org.hibernate.hql.internal.antlr.HqlsqlBaseWalker.fromElement(HqlsqlBaseWalker.java:3291)
at org.hibernate.hql.internal.antlr.HqlsqlBaseWalker.fromElementList(HqlsqlBaseWalker.java:3180)
at org.hibernate.hql.internal.antlr.HqlsqlBaseWalker.fromClause(HqlsqlBaseWalker.java:706)
at org.hibernate.hql.internal.antlr.HqlsqlBaseWalker.query(HqlsqlBaseWalker.java:562)
at org.hibernate.hql.internal.antlr.HqlsqlBaseWalker.selectStatement(HqlsqlBaseWalker.java:299)
at org.hibernate.hql.internal.antlr.HqlsqlBaseWalker.statement(HqlsqlBaseWalker.java:247)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:219)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:197)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1736)
at com.spring.bean.respistory.BookShopDaoImpl.findBookPriceByIsbn(BookShopDaoImpl.java:21)
at com.spring.bean.services.BookShopServiceImpl.purchase(BookShopServiceImpl.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy14.purchase(Unknown Source)
at com.spring.bean.services.CashierImpl.checkout(CashierImpl.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy15.checkout(Unknown Source)
at com.spring.bean.entity.MainTest.run(MainTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:941)
at com.spring.bean.respistory.BookShopDaoImpl.getCurrentSession(BookShopDaoImpl.java:15)
at com.spring.bean.respistory.BookShopDaoImpl.findBookPriceByIsbn(BookShopDaoImpl.java:21)
at com.spring.bean.services.BookShopServiceImpl.purchase(BookShopServiceImpl.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy14.purchase(Unknown Source)
at com.spring.bean.services.CashierImpl.checkout(CashierImpl.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy15.checkout(Unknown Source)
at com.spring.bean.entity.MainTest.run(MainTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
超哥说是因为用getCurrentSession(),hibernate4.0不常用导致的,建议我换成opensession(),试验完发现dao层的所有方法都没问题,批量购书的接口加的事物required_new添加的注解无效了,提示余额不足,
度娘后,才明白
1 getCurrentSession创建的session会和绑定到当前线程,而openSession不会。
2 getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭
这里getCurrentSession本地事务(本地事务:jdbc)时 要在配置文件里进行如下设置
* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property>
getCurrentSession () 使用当前的session
openSession() 重新建立一个新的session