Java有transient关键字。为什么JPA有@Transient而不是简单地使用已经存在的java关键字?
当前回答
I will try to answer the question of "why". Imagine a situation where you have a huge database with a lot of columns in a table, and your project/system uses tools to generate entities from database. (Hibernate has those, etc...) Now, suppose that by your business logic you need a particular field NOT to be persisted. You have to "configure" your entity in a particular way. While Transient keyword works on an object - as it behaves within a java language, the @Transient only designed to answer the tasks that pertains only to persistence tasks.
其他回答
Java的transient关键字用于表示字段不被序列化,而JPA的@Transient注释用于表示字段不被持久化到数据库中,也就是说,它们的语义是不同的。
因为它们有不同的含义。@Transient注释告诉JPA提供者不要持久化任何(非瞬态的)属性。另一个告诉序列化框架不要序列化某个属性。您可能希望有一个@Transient属性并仍然序列化它。
正如其他人所说,@Transient用于标记不应该持久化的字段。请看这个简短的例子:
public enum Gender { MALE, FEMALE, UNKNOWN }
@Entity
public Person {
private Gender g;
private long id;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public Gender getGender() { return g; }
public void setGender(Gender g) { this.g = g; }
@Transient
public boolean isMale() {
return Gender.MALE.equals(g);
}
@Transient
public boolean isFemale() {
return Gender.FEMALE.equals(g);
}
}
当这个类被提供给JPA时,它持久化了性别和id,但不会尝试持久化helper布尔方法——如果没有@Transient,底层系统会抱怨实体类Person缺少setMale()和setFemale()方法,因此根本不会持久化Person。
如果你只是想要一个字段不会被持久化,无论是transient还是@Transient工作。但问题是,既然“瞬态”已经存在,为什么要@Transient。
因为@Transient字段仍然会被序列化!
假设你创建一个实体,做一些cpu消耗的计算来得到一个结果,这个结果不会保存在数据库中。但是您希望将实体发送给其他Java应用程序以通过JMS使用,那么您应该使用@Transient,而不是JavaSE关键字transient。因此,运行在其他vm上的接收器可以节省重新计算的时间。
I will try to answer the question of "why". Imagine a situation where you have a huge database with a lot of columns in a table, and your project/system uses tools to generate entities from database. (Hibernate has those, etc...) Now, suppose that by your business logic you need a particular field NOT to be persisted. You have to "configure" your entity in a particular way. While Transient keyword works on an object - as it behaves within a java language, the @Transient only designed to answer the tasks that pertains only to persistence tasks.
推荐文章
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- Spring引导——不是托管类型
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- “java”、“javaw”和“javaws”之间有什么区别?
- 将Date对象转换为日历对象
- 在Java中保存最后N个元素的大小有限的队列