gpt4 book ai didi

java - 关系表的 Spring JPA Repository 查询过滤器

转载 作者:搜寻专家 更新时间:2023-11-01 02:43:29 24 4
gpt4 key购买 nike

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

PersonCompany 之间的关系是多对多的。关系表 Employee 具有到 PersonCompany 的 FK,以及一个 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;
}

我是否在 CompanyEmployeeJPARepository 上使用了 @Query?我该如何应对?

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

最佳答案

巴勃罗,
我们公司正在将我们现有的Spring/MyBatis代码转换为Spring Data JPA,所以我一直在学习Spring Data JPA 几个星期。我显然不是专家,但我想出了一个类似于您的示例,可能会对您有所帮助。

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

我没有找到将开始/结束日期放入 company_person 连接表的方法,因此我为此制作了一个单独的(第 4 个表)。我用 Java 类实体 EmploymentRecord 将其命名为 employment_record。它具有组合主键(companyId、personId)和开始/结束日期。

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

我做了一个 Spring Boot Application 类来测试它。我在 PersonOneToMany 上使用了 CascadeType.ALL。在我的应用程序测试中,我测试了我可以更改分配给一个人的公司,并且 Spring Data 将所有需要的更改传播到 Company 实体和连接表。

但是,我必须通过其存储库手动更新 EmploymentRecord 实体。例如,我每次为一个人添加公司时都必须添加一个 start_date。然后,在我从那个人那里删除那家公司时添加一个结束日期。可能有某种方法可以自动执行此操作。 Spring/JPA 审计功能是可能的,所以检查一下。

问题的答案:

how can I retrieve a list of Person (I am interested in the person attributes) that are employees of a specific company?

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

来自 Application.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);
}

以下是我认为有用的一些引用资料:

Spring Data JPA tutorial
Join Table example

人.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

}

公司.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
}

就业记录.java:

@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
}

MySql 脚本,createTables.sql:

DROP TABLE IF EXISTS `test`.`company_person`;
DROP TABLE IF EXISTS `test`.`employment_record`;
DROP TABLE IF EXISTS `test`.`company`;
DROP TABLE IF EXISTS `test`.`person`;

CREATE TABLE `company` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL DEFAULT '',
`address` varchar(500) DEFAULT '',
`version_id` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `person` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL DEFAULT '',
`address` varchar(500) DEFAULT '',
`version_id` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/* Join table */
CREATE TABLE `company_person` (
`company_id` int NOT NULL,
`person_id` int NOT NULL,
PRIMARY KEY (`person_id`,`company_id`),
KEY `company_idx` (`company_id`),
KEY `person_idx` (`person_id`),
CONSTRAINT `fk_person` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_company` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/* Employment records */
CREATE TABLE `employment_record` (
`company_id` int NOT NULL,
`person_id` int NOT NULL,
`start_date` datetime,
`end_date` datetime,
`version_id` int NOT NULL,
PRIMARY KEY (`person_id`,`company_id`),
KEY `empl_company_idx` (`company_id`),
KEY `empl_person_idx` (`person_id`),
CONSTRAINT `fk_empl_person` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_empl_company` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

关于java - 关系表的 Spring JPA Repository 查询过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28183939/

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