JPQL和嵌入式密钥中的简单多对多选择查询

时间:2012-11-30 11:33:52

标签: java database jpql

我有这个模型,只有两个实体,一个用于密钥的可嵌入实体和一个实体,其中该密钥作为id字段。

我想知道,如何编写简单的查询"给我一个id为5" "给我一个名字有人的所有功能"。

如果有可嵌入的密钥,我不明白如何访问这些信息......

我犹豫是否要重写我的模型,因为我必须在代码周围重写大量内容。

如何删除该关联表中的某些内容?我真的不知道哪种"方式"我应该采取措施来解决这个问题。

谢谢你们提示

@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

1 个答案:

答案 0 :(得分:2)

您似乎将这些映射为单个独立实体。如果你映射实体之间的关系,那么你应该能够通过简单地调用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"

我没有测试过这些代码,但它应该大致正确。