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

时间:2015-03-22 09:18:06

标签: java jpa annotations entity spring-data-jpa

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

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

1 个答案:

答案 0 :(得分:1)

假设您有一个使用@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>