gpt4 book ai didi

java - 是否可以通过扩展 POJO 来构建 JPA 实体?

转载 作者:IT老高 更新时间:2023-10-28 20:28:16 25 4
gpt4 key购买 nike

假设我有以下 POJO:

public class MyThing {
private int myNumber;
private String myData;
//assume getter/setter methods
}

现在可以将此 POJO 扩展为 JPA 实体吗?

@Entity
@Table(name = "my_thing")
public class MyThingEntity extends MyThing implements Serializable {
@Column(name = "my_number")
//?????????
@Column(name = "my_data")
//????????
}

我想将 POJO 与 JPA 实体分开。 POJO 存在于不同的项目中,并且通常在没有持久层的情况下使用,我的项目希望将其持久化到数据库中,并且这样做没有从 POJO 映射到实体并返回的开销。

我知道 JPA 实体是 POJO,但为了使用它,我必须包含一个实现 javax.persistence 的库,而使用相同基础对象的其他项目对持久层没有用处。

这可能吗?这是个好主意吗?

最佳答案

JPA 规范状态

Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.

@javax.persistence.MappedSuperclass 注解允许你定义这种映射

@MappedSuperclass
public class MyThing implements Serializable {
private int myNumber;
private String myData;

// getter's and setter's
}

@Entity
@Table(name="MY_THING")
public class MyThingEntity extends MyThing {


}

如 JPA 规范所述

The MappedSuperclass annotation designates a class whose mapping information is applied to the entities that inherit from it.

A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped superclass itself.

如果您需要覆盖 MyThing 定义的某些属性,请使用 @AttributeOverride(当您想要覆盖单个属性时)或 @AttributeOverrides(当您想要覆盖多个属性时)

@Entity
@Table(name="MY_THING")
@AttributeOverride(name="myData", column=@Column(name="MY_DATA"))
public class MyThingEntity extends MyThing {


}

@Entity
@Table(name="MY_OTHER_THING")
@AttributeOverrides({
@AttributeOverride(name="myData1", column=@Column(name="MY_DATA_1")),
@AttributeOverride(name="myData2", column=@Column(name="MY_DATA_2"))
})
public class MyOtherThingEntity extends MyThing {

}

如果你不想改变你的基类,你可以使用xml将它定义为@MappedSuperClass

注意:默认情况下,持久性提供程序将在 META-INF 目录中查找名为 orm.xml 的文件

<?xml version="1.0" encoding="UTF-8"?>

<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
<mapped-superclass class="MyThing">

</mapped-superclass>
</entity-mappings>

没有别的。如果要覆盖属性,请使用@AttributeOverride,如上所示

关于java - 是否可以通过扩展 POJO 来构建 JPA 实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2516329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com