Spring Data JPA实体的生命周期总结 (2)

结果:抛异常

1
2
3
4
5
6
7
8
9
  2019-01-26 00:00:34.090 ERROR 5228 --- [io-8080-exec-10] c.e.demo.controller.UserController : 持久化一个游离态的对象!
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.example.demo.entity.User; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.example.demo.entity.User
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:317) ~[spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253) ~[spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527) ~[spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.1.4.RELEASE.jar:5.1.4.RELEASE]

....
 

remove

不同状态下执行em.remove()方法产生结果:

瞬时态:对状态无影响,后台打印日志

托管态:转化为托管态

删除态:无影响,什么都不发生

游离态:抛异常Removing a detached instance com.example.demo.entity.User...

验证过程如下:

1.瞬时态

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  /**
* 删除new出来的对象
*@param id
* @return
*/
@RequestMapping("/removeNew")
public String removeNew(){
try {
User user = new User().setName("lxt").setNumber("007");
userDao.remove(user);
}catch (Exception e){
logger.error("删除(remove)一个new的对象!",e);
return REPONSE_ERR;
}
return REPONSE_SUCCESS;
}
 

步骤

:8080/user/removeNew

结果:返回SUCCESS!后台输出日志

1
  2019-01-26 00:17:32.811 INFO 10136 --- [nio-8080-exec-5] o.h.e.i.DefaultDeleteEventListener : HHH000114: Handling transient entity in delete processing
 

2.删除态

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwdjzd.html