gpt4 book ai didi

java - 在单独的文件中定义 JPA 实体图

转载 作者:行者123 更新时间:2023-11-30 03:30:20 24 4
gpt4 key购买 nike

是否可以在与实体定义不同的单独文件中为 JPA 实体(@NamedEntityGraph 注释)定义实体图?

如果我的项目变得有点复杂,我在这些定义的实体之前就会有一大堆丑陋/不可读的代码。

最佳答案

假设您有一个使用 @NamedEntityGraph 注释的实体,如下所示:

@Entity
@NamedEntityGraph(name = "Project.graph"
attributeNodes = {
@NamedAttributeNode(value = "deadline"),
@NamedAttributeNode(value = "employees", subgraph = "Employee.subgraph")},
...
subgraphs = {
@NamedSubgraph(name = "Employee.subgraph",
attributeNodes = {
@NamedAttributeNode(value = "salary")}
...
)}
)
public class Project {
...
@Temporal(TemporalType.DATE)
private Date deadline;

@OneToMany(mappedBy="project", cascade = CascadeType.PERSIST)
private Collection<Employee> employees;
...
}

在 persistence.xml 中添加对 XML 映射文件的引用(假设为 orm.xml):

...
<mapping-file>META-INF\orm.xml</mapping-file>
...

对于上面的 @NamedEntityGraph 可以定义如下:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd"
version="2.1">
...
<entity class="com.example.Project">
<named-entity-graph>
<named-attribute-node name="deadline" />
<named-attribute-node name="projects" subgraph="Employee.subgraph" />
...
<subgraph name="Employee.subgraph">
<named-attribute-node name="salary" />
...
</subgraph>
</named-entity-graph>
</entity>
</entity-mappings>

关于java - 在单独的文件中定义 JPA 实体图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29192721/

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