Java Spring Hibernate 集成错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24340800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Hibernate Integration error
提问by user3762635
I have been receiving the following error when trying to integrate spring with hibernate in a standalone application.
尝试在独立应用程序中将 spring 与 hibernate 集成时,我收到以下错误。
Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1135)
at org.springframework.orm.hibernate4.HibernateTemplate.doInHibernate(HibernateTemplate.java:620)
at org.springframework.orm.hibernate4.HibernateTemplate.doInHibernate(HibernateTemplate.java:617)
at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:308)
at org.springframework.orm.hibernate4.HibernateTemplate.save(HibernateTemplate.java:617)
at CarDAO.insert(CarDAO.java:38)
at CarTest.main(CarTest.java:19)
Bean File:
豆文件:
public class Car {
int carid;
String carname;
public int getCarid() {
return carid;
}
public void setCarid(int carid) {
this.carid = carid;
}
public String getCarname() {
return carname;
}
public void setCarname(String carname) {
this.carname = carname;
}
}
My hibernate mapping file:
我的休眠映射文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Car" table="Car">
<id name="carid" column="carid"/>
<property name="carname" column="carname"/>
</class>
</hibernate-mapping>
CarDAO:
卡道:
import javax.persistence.EntityManager;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
//import org.springframework.transaction.annotation.Transactional;
public class CarDAO {
HibernateTemplate template;
EntityManager entityManager;
TransactionTemplate template1;
public HibernateTemplate getTemplate() {
return template;
}
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
@Transactional
@Scope("session")
public void insert(Car c){
//template.getSessionFactory().getCurrentSession().setFlushMode(org.hibernate.FlushMode.AUTO);
//entityManager.setFlushMode(javax.persistence.FlushModeType.AUTO);
// session.setFlushMode(FlushMode.AUTO);
template.save(c);
entityManager.flush();
}
}
ApplicationContext.xml:
应用上下文.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="datasourceBean" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionfactoryBean" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="datasourceBean"/>
<property name="mappingResources">
<list>
<value>Car.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionfactoryBean"></property>
<!-- <property name="flushModeName" value="FLUSH_COMMIT"/> -->
</bean>
<bean id="CarDAO" class="CarDAO">
<property name="template" ref="template"></property>
</bean>
</beans>
I have searched over the web for appropriate solution but was unable to find it.Please help thanks in advance
我已经在网上搜索了合适的解决方案,但找不到。请提前帮助谢谢
回答by EPerrin95
I have already had this error and i use transaction to solve it.
我已经有这个错误,我使用事务来解决它。
First of all, you need to declare the hibernate4 transaction bean. Just write the following code in your ApplicationContext.xml :
首先需要声明hibernate4事务bean。只需在 ApplicationContext.xml 中编写以下代码:
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionfactoryBean"/>
</bean>
Then, for DAO test, i used directly annotation such as @Transactional(readOnly = false)
above method which need to write in database (methods like save, update or delete). To production, i set up transactions in my service layer with AOP.
然后,对于DAO测试,我直接使用了@Transactional(readOnly = false)
上面需要写入数据库的方法(保存,更新或删除等方法)的注释。对于生产,我使用 AOP 在我的服务层中设置事务。
Some example :
this is one of may test method where i use @Transactional
:
一些例子:这是我使用的可能测试方法之一@Transactional
:
@Test
@Transactional(readOnly = false)
public void UpdateUser() {
long UserId = 1;
String UserFirstName = "some.FirstName";
String UserName = "some.Name";
User userToUpdate = userDAO.getUser(UserId);
userToUpdate.setFirstName(UserFirstName);
userToUpdate.setFamilyName(UserName);
userDAO.updateUser(userToUpdate);
User userUpdated = userDAO.getUser(UserId);
Assert.assertEquals(UserFirstName, userUpdated.getFirstName());
Assert.assertEquals(UserName, userUpdated.getFamilyName());
}
If i remove the @Transactional(readOnly = false)
, my test will fail with the same error as your :
如果我删除@Transactional(readOnly = false)
,我的测试将失败,并出现与您相同的错误:
UpdateUser(project.domain.dao.hibernate.UserDAOHibernateTest): Write operation
s are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into F
lushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
To production now, i set up transaction in service layer by means of AOP, in spring xml configuration :
现在生产,我通过AOP在服务层设置事务,在spring xml配置中:
<aop:config>
<aop:advisor id="managerTx" advice-ref="txAdvice" pointcut="execution(* *..service.manager.*Manager.*(..))"
order="1"/>
</aop:config>
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
<tx:method name="create*" propagation="REQUIRED" read-only="false" />
<tx:method name="save*" propagation="REQUIRED" read-only="false" />
<tx:method name="update*" propagation="REQUIRED" read-only="false" />
<tx:method name="delete*" propagation="REQUIRED" read-only="false" />
</tx:attributes>
</tx:advice>
You can configure a lot of another things with AOP, see spring docfor that.
您可以使用 AOP 配置许多其他内容,请参阅spring 文档。
I hope this will help you
我希望这能帮到您
回答by user5979134
I find the answer.But I don`t know the reason.The answer are as follows.you should join some code in beans.xml.
我找到了答案。但我不知道原因。答案如下。你应该在beans.xml中加入一些代码。
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<aop:config>
<aop:pointcut id="bussinessService"
expression="execution(public * com.yh.registration.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="exists" read-only="true" />
<tx:method name="add*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
回答by Seymur Asadov
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
回答by Seymur Asadov
If you're use spring mvc...
如果您使用的是 spring mvc ...
In dispatcher-servlet.xml
在 dispatcher-servlet.xml 中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<mvc:resources location="file:/C:/Users/seymur/Desktop/images/"
mapping="/resources/**" />
<mvc:annotation-driven />
<tx:annotation-driven />
<mvc:resources location="resources/" mapping="/temp/**" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<context:component-scan base-package="scanPackages" />
</beans>
In application-context.xml
在 application-context.xml 中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/webshoppingmitm" />
<property name="username" value="root" />
<property name="password" value="pass" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>packageEntity.EntityClass</value>
</list>
</property>
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<constructor-arg name="sessionFactory" ref="sessionFactory"></constructor-arg>
</bean>
</beans>