Spring JPA Repository查询过滤关系表

时间:2015-01-28 03:07:37

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

如果我在JPA实体之间存在多对多关系,如何检索特定公司员工的Person(我对人员属性感兴趣)列表?

PersonCompany之间的关系是多对多的。关系表Employee的FK为PersonCompany,start_date和end_date表示就业开始和结束的时间。

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "address")
    private String address;
}

@Entity
public class Company {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "address")
    private String address;
}

@Entity
public class CompanyEmployee {
    //note this is to model a relationship table. Am I doing this wrong?
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "start_date", nullable = false)
    private LocalDate startDate;

    @Column(name = "end_date", nullable = false)
    private LocalDate endDate;

    @ManyToOne
    private Company company;

    @ManyToOne
    private Person person;
}

我是否在@Query上使用了CompanyEmployeeJPARepository?我应该怎么解决它?

public interface CompanyEmployeeRepository extends JpaRepository<CompanyEmployee,Long> {
//
}

3 个答案:

答案 0 :(得分:2)

我以前有过hibernate JPA的经验但不是spring JPA。根据该知识,查询可能有用:

select cp.person from CompanyEmployee cp where cp.company.id = ?

答案 1 :(得分:2)

巴勃罗,
我们公司正在将现有的 Spring / MyBatis 代码转换为 Spring Data JPA ,因此我一直在学习 Spring Data JPA 几周。我显然不是专家,但我找到了一个类似于你的例子,可以帮助你。

我有PersonCompany类与您的类似,但(正如Jens所提到的),您需要带有OneToMany注释的列表。我使用了一个单独的连接表(名为company_person),它只有 companyId personId 列来维护多对多关系。请参阅下面的代码。

我没有看到将开始/结束日期放在company_person连接表中的方法,所以我为此做了一个单独的(第4个表)。我用Java类实体EmploymentRecord称它为employment_record。它具有组合主键(companyId,personId)和开始/结束日期。

您需要Person,Company和EmploymentRecord的存储库。我扩展了CrudRepository而不是JpaRepository。但是,您不需要连接表(company_record)的实体或存储库。

我制作了一个Spring Boot Application类来测试它。我在CascadeType.ALL的{​​{1}}上使用了Person。在我的应用程序测试中,我测试过我可以更改分配给某人的公司,Spring Data会传播OneToMany实体和连接表所需的所有更改。

但是,我必须通过其存储库手动更新Company个实体。例如,每次我向一个人添加公司时,我都必须添加一个start_date。然后,当我从该人那里删除该公司时添加end_date。可能有一些方法可以实现自动化。 Spring / JPA审核功能是可能的,所以请检查出来。

你的问题的答案:

  

如何检索Person列表(我对此人感兴趣   属性)是特定公司的员工吗?

您只需使用companyRepository的findOne(Long id)方法,然后使用getPersonList()方法。

来自Application.java的

片段:

EmploymentRecord

以下是我发现有用的一些参考资料:

Spring Data JPA tutorial
Join Table example

Person.java:

PersonRepository pRep = context.getBean(PersonRepository.class);
CompanyRepository cRep = context.getBean(CompanyRepository.class);
EmploymentRecordRepository emplRep = context.getBean(EmploymentRecordRepository.class);

...

// fetch a Company by Id and get its list of employees
Company comp = cRep.findOne(5L);
System.out.println("Found a company using findOne(5L), company= " + comp.getName());
System.out.println("People who work at " + comp.getName());
for (Person p : comp.getPersonList()) {
    System.out.println(p);
}

Company.java:

@Entity
public class Person {

    // no-arg constructor
    Person() { }

    // normal use constructor
    public Person(String name, String address) {
        this.name = name;
        this.address = address;
    }

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "address")
    private String address;

    @Version
    private int versionId;

    @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name="company_person",  
    joinColumns={@JoinColumn(name="person_id", referencedColumnName="id")},  
    inverseJoinColumns={@JoinColumn(name="company_id", referencedColumnName="id")})  
    private List<Company> companyList;  

    // Getters / setters

}

EmploymentRecord.java:

@Entity
public class Company {

    // no-arg constructor
    Company() { }

    // normal use constructor
    public Company(String name, String address) {
        this.name = name;
        this.address = address;
    }

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "address")
    private String address;

    @Version
    private int versionId;

    //@OneToMany(cascade=CascadeType.ALL)
    @OneToMany(fetch = FetchType.EAGER)
    @JoinTable(name="company_person",  
    joinColumns={@JoinColumn(name="company_id", referencedColumnName="id")},  
    inverseJoinColumns={@JoinColumn(name="person_id", referencedColumnName="id")})  
    private List<Person> personList;  

    // Getters / Setters
}

MySql脚本,createTables.sql:

@Entity
@IdClass(EmploymentRecordKey.class)
public class EmploymentRecord {

    // no-arg constructor
    EmploymentRecord() { }

    // normal use constructor
    public EmploymentRecord(Long personId, Long companyId, Date startDate, Date endDate) {
        this.startDate = startDate;
        this.endDate = endDate;
        this.companyId = companyId;
        this.personId = personId;
    }

    // composite key
    @Id
    @Column(name = "company_id", nullable = false)
    private Long companyId;

    @Id
    @Column(name = "person_id", nullable = false)
    private Long personId;

    @Column(name = "start_date")
    private Date startDate;

    @Column(name = "end_date")
    private Date endDate;

    @Version
    private int versionId;

    @Override
    public String toString() {
        return
                " companyId=" + companyId +
                " personId=" + personId +
                " startDate=" + startDate +
                " endDate=" + endDate +
                " versionId=" + versionId;
    }

    // Getters/Setters

}

// Class to wrap the composite key
class EmploymentRecordKey implements Serializable {

    private long companyId;
    private long personId;

    // no arg constructor
    EmploymentRecordKey() { }

    @Override
    public int hashCode() {
        return (int) ((int) companyId + personId);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (obj == this) return true;
        if (!(obj instanceof EmploymentRecordKey)) return false;
        EmploymentRecordKey pk = (EmploymentRecordKey) obj;
        return pk.companyId == companyId && pk.personId == personId;
    }

    // Getters/Setters
}

答案 2 :(得分:0)

您不需要为关系表创建单独的实体。

可以在两个实体内保持关系,

所以如果A和B处于多对多的关系中,

@Entity
class A {

@Id
Long id;
...

@ManyToMany(fetch=FetchType.LAZY)
@JoinTable(name="a_b",
            joinColumns={@JoinColumn(name="id_a", referencedColumnName="id")},
            inverseJoinColumns={@JoinColumn(name="id_b", referencedColumnName="id")})
List<B> bList;

...

}


@Entity
class B {

@Id
Long id;
...

@ManyToMany(fetch=FetchType.LAZY)
@JoinTable(name="a_b",
            joinColumns={@JoinColumn(name="id_b", referencedColumnName="id")},
            inverseJoinColumns={@JoinColumn(name="id_a", referencedColumnName="id")})
List<A> aList;

...

}

您现在可以在任一实体存储库上使用存储库查询,或者如果您在两者上都有params查询,则可以在其中的存储库中创建自定义查询。