我有这个模型,只有两个实体,一个用于键的可嵌入实体和一个该键作为 id 字段的实体。
我想知道,如何编写像“给我一个 id 5 的人的所有功能”或“给我一个名为 Somebody 的人的所有功能”这样的简单查询。
当存在可嵌入 key 时,我不明白如何访问这些信息......
我犹豫是否重写我的模型,因为我必须重写代码周围的大量内容。
我如何从关联表中删除一些内容?我只是真的不知道应该采取哪种“方式”来解决这个问题。
谢谢各位的指点
@Entity
@Table(name = "PERSON")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "person_id")
private Long id;
@Column(name = "name", unique = true)
private String name;
// .. getters and setters
@Entity
@Table(name = "FUNC")
public class Function {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "function_id")
private Long id;
@Column(name = "name")
private String name;
// .. getters and setter
@Embeddable
public class PersonFunctionPK {
@Column(name = "person_id")
private Long personId;
@Column(name = "function_id")
private Long functionId;
public PersonFunctionPK() {
}
PersonFunctionPK(Long personId, Long functionId) {
this.personId = personId;
this.functionId = functionId;
}
// .. getters and setter
@Entity
@Table(name = "PERSON_FUNC")
public class PersonFunction {
@EmbeddedId
protected PersonFunctionPK personFunctionPK;
public PersonFunction() {}
public PersonFunction(PersonFunctionPK personFunctionPK) {
this.personFunctionPK = personFunctionPK;
}
public PersonFunction(Long personId, Long functionId) {
this.personFunctionPK = new PersonFunctionPK(personId, functionId);
}
// .. getters and setter for personFunctionPK
最佳答案
您似乎将它们映射为单个独立实体。如果您映射实体之间的关系,那么您应该能够通过简单地调用 get 方法来完成大部分查询(不需要 jpql)
@Entity
@Table(name = "PERSON")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "person_id")
private Long id;
@Column(name = "name", unique = true)
private String name;
@ManyToMany(mappedBy = "persons", cascade=CascadeType.ALL)
private Collection<Function> functions;
// .. getters and setters
@Entity
@Table(name = "FUNC")
public class Function {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "function_id")
private Long id;
@Column(name = "name")
private String name;
@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name = "PERSON_FUNC",
joinColumns = {@JoinColumn(name = "function_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "person_id", referencedColumnName = "id")})
private Collection<Person> persons;
// .. getters and setter
现在,如果你得到一个 id 为 5 的人,你可以调用一个简单的 getter 来获取这个人的函数。如果您想要将一组函数分配给所有名为 Stefan 的人,您可能仍然需要使用 JPQL。不过,您仍然需要映射 @ManyToMany,因为在 JPQL 中您指定对象关系(而不是底层数据库)
select distinct f from Function f inner join f.persons p where p.name = "Stefan"
我还没有测试过这段代码,但它应该大致正确。
关于java - JPQL 中的简单多对多选择查询和可嵌入键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13644467/