- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 JPA2.0+hibernate3.2+Spring3.0.5+MySql5.5 来实现 DAO 功能,但是当我尝试将实体持久化到 DB 时,它不起作用并且只是抛出 javax.persistence.TransactionRequiredException。请参阅我的编码和配置。
1.实体
@Entity
@Table(name="booking_no")
public class BookingNo {
public BookingNo(){
};
@Id
@GeneratedValue
private Integer id;
@Column(unique=true,length=30)
private String prefix;
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)
public Object generateBookingNo(String customer) throws Exception{
logger.debug("generateBookingNo() start,generate booking no by customer:"+customer);
if(customer == null || customer.trim().length() == 0){
logger.error("generateBookingNo(),customer is empty,return null");
return null;
}
EntityManager em = emf.createEntityManager();
try{
Query query = em.createQuery("select b from BookingNo b where b.prefix='"+customer+"'");
Object object =null;
try{
object = query.getSingleResult();
}catch(NoResultException e){
logger.info("generateBookingNo(),not find id for customer["+customer+"],will save a initial record");
BookingNo bkNo = new BookingNo();
bkNo.setPrefix(customer);
logger.debug("generateBookingNo(),the bookingNo is:"+bkNo);
em.persist(bkNo);
//em.flush();
Object object2 =null;
try{
object2 = em.createQuery("select b.id from BookingNo b where b.prefix='"+customer+"'").getSingleResult();
}catch(Exception e2){
logger.error("get error when query customer ["+customer+"]",e);
return null;
}
return customer+"-"+object2;
}
if(object == null || !(object instanceof BookingNo)){
logger.error("generateBookingNo(),return nothing but not catch NoResultException,return null");
return null;
}
BookingNo bkNo =(BookingNo) object;
Integer newId = bkNo.getId()+1;
//Query query2 = em.createQuery("update BookingNo b set b.id="+newId+" where b.prefix='"+customer+"'");
Query query2 = em.createNativeQuery("update booking_no b set b.id="+newId+" where b.prefix='"+customer+"'");
int res = query2.executeUpdate();
logger.debug("generateBookingNo(),the to be update bookingNo is:"+bkNo+",the update result is:"+res);
//em.flush();
return customer+"-"+newId;
}catch(Exception e){
logger.error("get error in generateBookingNo()",e);
return null;
}finally{
em.close();
emf.close();
}
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="bookingEMF"/>
</bean>
<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost/booking"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
<property name="initialPoolSize" value="1"></property>
<property name="minPoolSize" value="1"></property>
<property name="maxPoolSize" value="20"></property>
<property name="maxIdleTime" value="60"></property>
<property name="acquireIncrement" value="5"></property>
<property name="idleConnectionTestPeriod" value="60"></property>
<property name="acquireRetryAttempts" value="20"></property>
<property name="breakAfterAcquireFailure" value="true"></property>
</bean>
<!-- Entity Manager Factory -->
<bean id="bookingEMF" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="booking"/>
<property name="dataSource" ref="dataSource1" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.transaction.flush_before_completion" value="true"/>
<entry key="hibernate.transaction.auto_close_session" value="true"/>
<entry key="hibernate.connection.release_mode" value="auto"/>
<entry key="hibernate.hbm2ddl.auto" value="update"/>
<entry key="format_sql" value="true"/>
<!-- <entry key="hibernate.transaction.manager_lookup_class" value="com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"/> -->
</map>
</property>
</bean>
<!-- JPA Vendor,Implementation is hibernate -->
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
<!-- DAO -->
<bean id="BookingDAO" class="com.chailie.booking.dao.impl.booking.BookingDAO" >
<property name="emf" ref="bookingEMF"/>
</bean>
@Test
public void testGenerateBookingNo(){
try {
BookingDAO dao = (BookingDAO) DAOFactory.getDAO("BookingDAO", DAOFactory.TYPE_APPLICATION);
dao.generateBookingNo("chailie");
//dao.generateBookingNo("chailie2");
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("get error",e);
}
}
23:15:46.817 [main] DEBUG org.hibernate.hql.ast.ErrorCounter - throwQueryException() : no errors
23:15:46.837 [main] DEBUG o.h.hql.ast.QueryTranslatorImpl - HQL: select b from com.chailie.booking.model.booking.BookingNo b where b.prefix='chailie'
23:15:46.837 [main] DEBUG o.h.hql.ast.QueryTranslatorImpl - SQL: select bookingno0_.id as id0_, bookingno0_.prefix as prefix0_ from booking_no bookingno0_ where bookingno0_.prefix='chailie'
23:15:46.837 [main] DEBUG org.hibernate.hql.ast.ErrorCounter - throwQueryException() : no errors
23:15:46.856 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
23:15:46.856 [main] DEBUG org.hibernate.jdbc.ConnectionManager - opening JDBC connection
23:15:46.891 [main] DEBUG org.hibernate.SQL - select bookingno0_.id as id0_, bookingno0_.prefix as prefix0_ from booking_no bookingno0_ where bookingno0_.prefix='chailie' limit ?
Hibernate: select bookingno0_.id as id0_, bookingno0_.prefix as prefix0_ from booking_no bookingno0_ where bookingno0_.prefix='chailie' limit ?
23:15:46.922 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open ResultSet (open ResultSets: 0, globally: 0)
23:15:46.926 [main] DEBUG org.hibernate.loader.Loader - result row: EntityKey[com.chailie.booking.model.booking.BookingNo#8]
23:15:46.935 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close ResultSet (open ResultSets: 1, globally: 1)
23:15:46.936 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
23:15:46.936 [main] DEBUG org.hibernate.jdbc.ConnectionManager - aggressively releasing JDBC connection
23:15:46.936 [main] DEBUG org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
23:15:46.939 [main] DEBUG org.hibernate.engine.TwoPhaseLoad - resolving associations for [com.chailie.booking.model.booking.BookingNo#8]
23:15:46.941 [main] DEBUG org.hibernate.engine.TwoPhaseLoad - done materializing entity [com.chailie.booking.model.booking.BookingNo#8]
23:15:46.942 [main] DEBUG o.h.e.StatefulPersistenceContext - initializing non-lazy collections
23:15:46.942 [main] DEBUG org.hibernate.jdbc.ConnectionManager - aggressively releasing JDBC connection
23:15:46.944 [main] DEBUG o.h.ejb.AbstractEntityManagerImpl - mark transaction for rollback
23:15:46.954 [main] ERROR c.c.b.d.booking.impl.BookingDAOTest - get error in generateBookingNo()
javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.ejb.QueryImpl.executeUpdate(QueryImpl.java:48) [hibernate-entitymanager-3.4.0.GA.jar:3.4.0.GA]
at com.chailie.booking.dao.impl.booking.BookingDAO.generateBookingNo(BookingDAO.java:104) [classes/:na]
at com.chailie.booking.dao.impl.booking.BookingDAO$$FastClassByCGLIB$$2898182b.invoke(<generated>) [cglib-2.2.jar:na]
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191) [cglib-2.2.jar:na]
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) [spring-tx-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at com.chailie.booking.dao.impl.booking.BookingDAO$$EnhancerByCGLIB$$58d6a935.generateBookingNo(<generated>) [cglib-2.2.jar:na]
at com.chailie.booking.dao.booking.impl.BookingDAOTest.testGenerateBookingNo(BookingDAOTest.java:42) [test-classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [na:1.7.0_15]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [na:1.7.0_15]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [na:1.7.0_15]
at java.lang.reflect.Method.invoke(Unknown Source) [na:1.7.0_15]
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) [junit-4.7.jar:na]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) [junit-4.7.jar:na]
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) [junit-4.7.jar:na]
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) [junit-4.7.jar:na]
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76) [junit-4.7.jar:na]
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner.run(ParentRunner.java:236) [junit-4.7.jar:na]
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53) [surefire-junit4-2.10.jar:2.10]
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123) [surefire-junit4-2.10.jar:2.10]
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104) [surefire-junit4-2.10.jar:2.10]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [na:1.7.0_15]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [na:1.7.0_15]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [na:1.7.0_15]
at java.lang.reflect.Method.invoke(Unknown Source) [na:1.7.0_15]
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) [surefire-api-2.10.jar:2.10]
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) [surefire-booter-2.10.jar:2.10]
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175) [surefire-booter-2.10.jar:2.10]
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107) [surefire-booter-2.10.jar:2.10]
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68) [surefire-booter-2.10.jar:2.10]
23:15:46.958 [main] INFO o.hibernate.impl.SessionFactoryImpl - closing
23:15:46.960 [main] DEBUG o.h.transaction.JDBCTransaction - commit
23:15:46.962 [main] DEBUG o.h.transaction.JDBCTransaction - re-enabling autocommit
23:15:46.962 [main] DEBUG o.h.transaction.JDBCTransaction - committed JDBC Connection
23:15:46.962 [main] DEBUG org.hibernate.jdbc.ConnectionManager - aggressively releasing JDBC connection
23:15:46.963 [main] DEBUG org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
最佳答案
在你做之前 em.persist()
, 得到一个 EntityTransaction
对象(比如 et
),通过做 em.getTransaction()
,然后做一个 et.begin()
.完成后 em.persist()
,做一个 et.commit()
.
关于spring - javax.persistence.TransactionRequiredException : Executing an update/delete query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16196142/
我写了这个课: class StaticList { private: int headFree; int headList; int locNe
我目前正在使用 SQL Server Management Studio 2005,我遇到了一些问题,但首先是我的 DB 架构的摘录(重要的): imghack link to the image 我
范围:两个表。创建新顾客时,他们会将一些有关他们的信息存储到第二个表中(这也是使用触发器完成的,它按预期工作)。这是我的表结构和关系的示例。 表 1-> 赞助人 +-----+---------+--
我想知道,在整个程序中,我使用了很多指向 cstrings 的 char* 指针,以及其他指针。我想确保在程序完成后删除所有指针,即使 Visual Studio 和 Code Blocks 都为我做
考虑以下代码: class Foo { Monster* monsters[6]; Foo() { for (int i = 0; i < 6; i++)
关于 this page , 是这么写的 One reason is that the operand of delete need not be an lvalue. Consider: delet
我无法在 DELETE CASCADE ON UPDATE CASCADE 上添加外键约束。 我使用两个简单的表格。 TAB1 有 2 列:ID int(10) unsigned NOT NULL A
你好,有没有办法把它放在一个声明中? DELETE e_worklist where wbs_element = '00000000000000000054TTO'. DELETE e_workli
我有一个表,它是我系统的核心,向我的客户显示的所有结果都存储在那里。它增长得非常快,因此每 3 小时我应该删除早于 X 的记录以提高性能。 仅删除这些记录就足够了,还是应该在删除后运行优化表? 我正在
这个问题在这里已经有了答案: delete vs delete[] operators in C++ (7 个答案) 关闭 9 年前。 做和做有什么区别: int* I = new int[100]
为什么这段代码是错误的?我是否遗漏了有关 delete 和 delete[] 行为的内容? void remove_stopwords(char** strings, int* length) {
当我使用 new [] 申请内存时。最后,我使用 delete 来释放内存(不是 delete[])。会不会造成内存泄漏? 两种类型: 内置类型,如 int、char、double ... 我不确定。
所以在代码审查期间,我的一位同事使用了 double* d = new double[foo]; 然后调用了 delete d。我告诉他们应该将其更改为 delete [] d。他们说编译器不需要基本
范围:两个表。当一个新顾客被创建时,他们将一些关于他们的信息存储到第二个表中(这也是使用触发器完成的,它按预期工作)。这是我的表结构和关系的示例。 表 1-> 赞助人 +-----+---------
C++14 介绍 "sized" versions of operator delete ,即 void operator delete( void* ptr, std::size_t sz ); 和
我正在执行类似的语句 DELETE FROM USER WHERE USER_ID=1; 在 SQLDeveloper 中。 由于用户在许多表中被引用(例如用户有订单、设置等),我们激活了 ON DE
出于某种原因,我找不到我需要的确切答案。我在这里搜索了最后 20 分钟。 我知道这很简单。很简单。但由于某种原因我无法触发触发器.. 我有一个包含两列的表格 dbo.HashTags |__Id_|_
这是我的代码: #include #include #include int main() { setvbuf(stdout, NULL, _IONBF, 0); setvbuf
是否可以在 postgres 中使用单个命令删除所有表中的所有行(不破坏数据库),或者在 postgres 中级联删除? 如果没有,那么我该如何重置我的测试数据库? 最佳答案 is it possib
我想删除一些临时文件的内容,所以我正在开发一个小程序来帮我删除它们。我有这两个代码示例,但我对以下内容感到困惑: 哪个代码示例更好? 第一个示例 code1 删除文件 1 和 2,但第二个示例 cod
我是一名优秀的程序员,十分优秀!