【发布时间】:2015-02-01 20:58:03
【问题描述】:
问题:无法通过 User 对象在 Spring Controller 中添加 Address 对象。
User 和 Address 类 -> @Entity
User 有一个 List<Address> 和 FetchType=LAZY
@Repository
public class UserDao{
@Autowired
private SessionFactory sessionFactory;
...
public User get(String username) {
Session session = sessionFactory.getCurrentSession();
return (User)session.get(User.class, username);
}
...
public void update(User user){
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(user);
}
...
}
@Service
@Transnational
public class UserService{
@AutoWired
private UserDao userDao;
...
@Transactional(readOnly = true)
public User get(String username) {
Session session = sessionFactory.getCurrentSession();
return (User)session.get(User.class, username);
}
public void update(User user){
userDao.update(user);
}
...
}
@Controller
public class UserController{
@AutoWired
private UserService userService;
....
public String update(){
User user = userService.get("user0001");
user.getAddressList.add(new Address("new street"));
return "update";
}
}
Spring.xml
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="packagesToScan" value="com.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
一切正常。但我无法更改 @Controller 内的 user 对象。
当user 对象在@Controller 级别发生变化时,该对象不涉及此类Hibernate 会话。不知何故,该对象超出了休眠上下文。
@Controller 中的 .add(new Address("new street")); 语句发生错误。
为什么禁止更改通过 Hibernate 会话接收的 Controller 内的对象?
我遵循的方式不正确?如果不是,我做错了什么?
--Spring 4,休眠 4
【问题讨论】: