如何在检索后设置瞬态字段

如何在检索后设置瞬态字段

本文介绍了Spring Data JPA - 如何在检索后设置瞬态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Spring Data JPA 的 JpaRepository 方法获取实体后,例如findOnefindBy... 等,我想知道自动执行一些自定义代码的最佳方法是什么,比如初始化一些瞬态字段.

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.

换句话说,假设我有一个带有 fullName 瞬态字段的 User 实体,它应该设置为 firstNamelastName 的串联> 从数据库中获取后,我该怎么办?

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.

如果你真的需要对实体加载做一些处理,那么注册一个@PostLoad实体生命周期回调:

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 - 如何在检索后设置瞬态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 21:25