我为表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);
}
我应该为联接表创建另一个实体类吗?有人可以给我一些指示的方式吗?
最佳答案
您可以为联接表创建一个实体类,但是不需要,您可能不需要。这样只会创建更多要维护的代码。如果联接表中有需要查询的数据,则应为联接表创建一个实体。 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; }