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

结果:返回ERROR!抛异常

1
2
3
4
5
6
7
  2019-01-26 00:38:18.037 ERROR 10136 --- [nio-8080-exec-3] c.e.demo.controller.UserController : 刷新(refresh)一个new的对象!

org.springframework.dao.InvalidDataAccessApiUsageException: Entity not managed; nested exception is java.lang.IllegalArgumentException: Entity not managed
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:373) ~[spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255) ~[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]
 

2.托管态:

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  /**
* 刷新托管态对象
*@param id
* @return
*/
@RequestMapping("/refreshManaged/{id}")
public String refreshManaged(@PathVariable("id")Long id){
try {
User user = userDao.findById(id);
userDao.refreshManaged(user);
}catch (Exception e){
logger.error("刷新(refresh)一个托管态的对象!",e);
return REPONSE_ERR;
}
return REPONSE_SUCCESS;
}
------------------------------------------------------------------
/**
* 刷新托管态的对象
*
* @param user
*/
@Override
public void refreshManaged(User user) {
user.setName("refresh before!");
refresh(user);
logger.info("user:"+user);
}
 

步骤

:8080/user/list,获取`id`

:8080/user/refreshManaged/{id},返回`SUCCESS`

:8080/user/list

结果:数据库中数据并无变化,日志打印为数据库中查询出的值,并未打印refresh before!

3.删除态

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  /**
* 刷新删除态对象
*@param id
* @return
*/
@RequestMapping("/refreshRemove/{id}")
public String refreshRemove(@PathVariable("id")Long id){
try {
User user = userDao.findById(id);
userDao.refreshRemove(user);
}catch (Exception e){
logger.error("刷新(refresh)一个删除态的对象!",e);
return REPONSE_ERR;
}
return REPONSE_SUCCESS;
}
----------------------------------------------------------------------
/**
* 刷新删除态的对象
*
* @param user
*/
@Override
public void refreshRemove(User user) {
remove(user);
user.setName("refresh remove before!");
refresh(user);
user.setName("refresh remove after!");
}
 

步骤

:8080/user/list,获取`id`

:8080/user/refreshRemove/{id}

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

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