【发布时间】:2018-03-27 01:54:35
【问题描述】:
我有 2 个实体 - 具有映射 @ManyToOne 的用户和角色。我想更改用户角色,但角色也需要更新。
用户实体:
@ManyToOne
@JoinColumn(name = "role_id", insertable = false, updatable = false)
private Role role;
角色实体:
@OneToMany(mappedBy = "role")
private Set<User> users;
我得到的错误是:
java.lang.IllegalStateException: org.hibernate.TransientObjectException: 对象引用了一个未保存的瞬态实例 - 在查询刷新之前保存瞬态实例:com.spring.model.Role 在 org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:144) 在 org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155) 在 org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162) 在 org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1434)
我在 DB 中的表没有使用 CASCADE UPDATE 或 INSERT 设置。我无法找到合适的解决方案。感谢您的帮助
编辑:
这就是我更新用户的方式
public void update(User user) {
User entity = dao.findById(user.getId());
if(entity!=null) {
entity.setRole(user.getRole());
}
}
编辑2:
我的休眠配置
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.spring.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {
@Autowired
private Environment environment;
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.spring.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
【问题讨论】:
-
您能否向我们展示您用于更改用户角色的代码的最小示例?
-
@Ruslan 是的,我找到了那个帖子,但对我没有帮助
-
您能否展示代码如何为
update(User user)填充用户对象?以及使用最新代码的实体。