JPA 瞬态信息在创建时丢失 [英] JPA transient information lost on create

查看:21
本文介绍了JPA 瞬态信息在创建时丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有瞬态字段的实体.当我想创建对象的新实例时,我丢失了临时信息.以下示例演示了该问题.为了这个例子,我们假设 barness 是一个瞬态场.

I have an entity with a transient field. When I want to create a new instance of the object I lose my transient information. The following example demonstrates the issue. For the sake of the example let's say that barness is a transient field.

FooEntity fooEntity = new FooEntity();
fooEntity.setFoobosity(5);
fooEntity.setBarness(2);
fooEntity = fooEntityManager.merge(fooEntity);
System.out.println(fooEntity.getFoobosity()); //5
System.out.println(fooEntity.getBarness()); //0 (or whatever default barness is)

有没有办法维护我的临时信息?

Is there any way to maintain my transient information?

推荐答案

这或多或少按设计工作.瞬态的语义正是 数据不持久化.从 entityManager.merge(obj) 返回的实体实际上是一个全新的实体,它维护传递给 merge 的对象的状态(状态,在这种情况下,是任何不属于持久对象).这在 JPA 规范中有详细说明.注意:可能有 JPA 实现会在对象合并后维护瞬态字段(仅仅是因为它们返回相同的对象),但规范不保证这种行为.

This is, more or less, working as designed. The semantics of transient are precisely that the data is not persisted. The entity returned from entityManager.merge(obj) is, in fact, an entirely new entity that maintains the state of the object passed into merge (state, in this context, being anything that is not part of the persistent object). This is detailed in the JPA spec. Note: There may be JPA implementations that do maintain the transient field after the object is merged (simply because they return the same object), but this behavior is not guaranteed by the spec.

基本上你可以做两件事:

There are essentially two things you can do:

  1. 决定持久化瞬态字段.如果您在将类合并到持久性上下文中后需要它,它似乎并不是真正的瞬态.

  1. Decide to persist the transient field. It doesn't really seem to be transient if you need it after merging the class into the persistence context.

在持久化对象之外维护transient字段的值.如果这满足您的需求,您可能需要重新考虑域类的结构;如果这个字段不是域对象状态的一部分,它真的不应该在那里.

Maintain the value of the transient field outside of the persistent object. If this is what meets your needs, you may want to rethink the structure of your domain class; if this field is not part of the state of the domain object it really shouldn't be there.

最后一件事:我发现域类上的瞬态字段的主要用例是划分派生字段,即可以根据类的持久字段重新计算的字段.

One final thing: the main use case I've found for transient fields on domain classes is to demarcate derived fields, i.e., fields that can be recalculated based on the persistent fields of the class.

这篇关于JPA 瞬态信息在创建时丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆