Spring Data JPA - 如何在检索后设置瞬态字段 [英] Spring Data JPA - how to set transient fields after retrieval
问题描述
使用Spring Data JPA的 JpaRepository
方法获取实体后,例如 findOne
, findBy ...
等等,我想知道什么是自动执行某些自定义的最佳方法代码,比如初始化一些瞬态字段。换句话说,假设我有一个用户实体,其中包含 fullName
临时字段,应该从数据库中提取后设置为 firstName
和 lastName
的串联,我应该怎么做首先,如果所有你想要的全名只是写一个方法,动态连接forename /姓氏。????????????它不一定是一个字段。
如果您确实需要对实体加载进行一些处理,请注册一个 @PostLoad
实体生命周期回调:
public class MyEntity {
@PostLoad
//由实体负载框架调用。
public void doStuff(){
fullName = forename ++ surname;
}
//替代
public String getFullName(){
return forename ++ surname;
}
https://en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Example_of_Entity_event_annotations
After an entity is fetched using the JpaRepository
methods of Spring Data JPA, e.g. findOne
, findBy...
, etc., I was wondering what would be the best way to automatically execute some custom code, say to initialize some transient fields.
In other words, suppose I have a User entity with a fullName
transient field, which should be set as a concatenation of firstName
and lastName
after fetching from the database, what should I do?
Firstly, if all you want if full name just write a method that concatenates forename/surname on the fly. It doesn't have to be a field.
If you really need to do some processing on Entity load then register a @PostLoad
entity lifecycle callback:
public class MyEntity{
@PostLoad
//invoked by framework on entity load.
public void doStuff(){
fullName = forename + " " + surname;
}
//alternative
public String getFullName(){
return forename + " " + surname;
}
https://en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Example_of_Entity_event_annotations
这篇关于Spring Data JPA - 如何在检索后设置瞬态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!