在Hibernate中加入Table和OneToMany关系

时间:2013-07-08 20:50:05

标签: java sql hibernate join dao

我为表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);
}

我应该为Join Table创建另一个实体类吗?有人可以给我一些指示方式吗?

1 个答案:

答案 0 :(得分: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; }