2

我为表 HOBBY 和 STUDENT 创建了两个实体,但是我很难从联接表中检索我需要的信息。

这是架构:

STUDENT              STUDENT_HOBBY        HOBBY
--------             -----------          --------
id ------------------ student_id
name                  hobby_id ---------- id
lastname                                  hobby_name    
---------             ----------          --------

where
Student to student_hobby = one to many
Hobby to student_hobby = one to many
(that means a student may have many hobbies and a hobby can belong to more than one student)

这是学生实体类:

@Entity
@Table(name="STUDENT")
public class Student {

    @OneToMany
    @JoinTable(name="student_hobbies", joinColumns=@JoinColumn(name="student_id"),
       inverseJoinColumns=@JoinColumn(name="hobby_id"))
    private Collection<Hobby> hobbies;

    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;

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

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

    // Getters and setters here
}

这是 Hobby 实体类:

@Entity
@Table(name="HOBBY")
public class Hobby {

    @OneToMany
    @JoinTable(name="student_hobbies", joinColumns=@JoinColumn(name="hobby_id"),
       inverseJoinColumns=@JoinColumn(name="student_id"))
    private Collection<Student> students;

    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;

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

    // Getters and setters here
}

现在我想实现以下DAO,但我不知道具体该怎么做:

public interface MyDAO {
    public void addHobbyForStudent(int student_id, int hobby_id);   
    public void RemoveHobbyForStudent(int student_id, int hobby_id);
}

我应该为联接表创建其他实体类吗?有人可以给我一些指示吗?

4

1 回答 1

2

可以为连接表创建一个实体类,但您不需要而且您可能不应该这样做。这只会创建更多需要维护的代码。如果连接表中有需要查询的数据,则应该为连接表创建一个实体。EG:如果连接表中有 start_time 或其他内容,并且您希望能够看到 start_time。

当您避免连接表实体时,您应该使用@ManyToMany注释。我链接到的文档提供了一些很好的例子来说明如何做到这一点:

Example 1:

// In Customer class:

@ManyToMany
@JoinTable(name="CUST_PHONES")
public Set<PhoneNumber> getPhones() { return phones; }

// In PhoneNumber class:

@ManyToMany(mappedBy="phones")
public Set<Customer> getCustomers() { return customers; }

Example 2:

// In Customer class:

@ManyToMany(targetEntity=com.example.PhoneNumber.class)
public Set getPhones() { return phones; }

// In PhoneNumber class:

@ManyToMany(targetEntity=com.example.Customer.class, mappedBy="phones")
public Set getCustomers() { return customers; }

Example 3:

// In Customer class:

@ManyToMany
@JoinTable(name="CUST_PHONE",
    joinColumns=
        @JoinColumn(name="CUST_ID", referencedColumnName="ID"),
    inverseJoinColumns=
        @JoinColumn(name="PHONE_ID", referencedColumnName="ID")
    )
public Set<PhoneNumber> getPhones() { return phones; }

// In PhoneNumberClass:

@ManyToMany(mappedBy="phones")
public Set<Customer> getCustomers() { return customers; }
于 2013-07-08T20:53:57.173 回答