下面的示例工作正常,但是我希望您检查这是否是好方法,因为我以前没有这样的要求,我很好奇应该如何完成。
我有三个表:EMPLOYEE、MEETING、EMPLOYEE_MEETING,并且只有两个映射用于 EMPLOYEE 和 MEETING 之间的多对多关系。看来我能够插入、加载和更新所有内容。我想要实现的不是为关系创建额外的映射、DAO 和单独的模型。
CREATE TABLE "employee_meeting" (
"employee_id" bigint(20) NOT NULL,
"meeting_id" bigint(20) NOT NULL,
"opinion" varchar(50) DEFAULT NULL,
PRIMARY KEY ("employee_id","meeting_id"),
KEY "FK_MEETING" ("meeting_id"),
CONSTRAINT "FK_EMPLOYEE" FOREIGN KEY ("employee_id") REFERENCES "employee" ("employee_id"),
CONSTRAINT "FK_MEETING" FOREIGN KEY ("meeting_id") REFERENCES "meeting" ("meeting_id")
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
<hibernate-mapping package="net.viralpatel.hibernate">
<class name="Employee" table="EMPLOYEE">
<id name="employeeId" column="EMPLOYEE_ID">
<generator class="native" />
</id>
<property name="firstname" />
<property name="lastname" column="lastname" />
<set name="meetings" table="EMPLOYEE_MEETING" inverse="false" lazy="false" fetch="select" cascade="all" >
<key column="EMPLOYEE_ID" />
<composite-element class="EmployeeMeeting">
<parent name="employee" />
<many-to-one name="meeting" column="MEETING_ID" not-null="true" cascade="all"
class="Meeting" />
<property name="opinion" column="OPINION" />
</composite-element>
</set>
</class>
<class name="Meeting" table="MEETING">
<id name="meetingId" type="java.lang.Long"
column="MEETING_ID">
<generator class="native" />
</id>
<property name="subject" column="SUBJECT" />
<property name="meetingDate" type="date" column="MEETING_DATE" />
</class>
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Meeting meeting1 = new Meeting("Quaterly Sales meeting");
Meeting meeting2 = new Meeting("Weekly Status meeting");
Employee employee1 = new Employee("Sergey", "Brin");
Employee employee2 = new Employee("Larry", "Page");
session.save(meeting1);
EmployeeMeeting em = new EmployeeMeeting(employee1, meeting1, "BAD");
employee1.getMeetings().add(em);
session.save(employee1);
session.save(employee2);
session.getTransaction().commit();
session.evict(employee1);
session.beginTransaction();
Employee e1 = (Employee) session.load(Employee.class, employee1.getEmployeeId());
EmployeeMeeting em2 = e1.getMeetings().iterator().next();
System.out.println("Test1:" + em2.getOpinion());
em2.setOpinion("BETTER");
session.save(e1);
session.getTransaction().commit();
session.evict(e1);
session.beginTransaction();
Employee e2 = (Employee) session.load(Employee.class, employee1.getEmployeeId());
System.out.println("Test2:" + e2.getMeetings().iterator().next().getOpinion());
System.out.println("Test2:" + e2.getMeetings().iterator().next().getMeeting().getMeetingId());
System.out.println("Test2:" + e2.getMeetings().iterator().next().getEmployee().getEmployeeId());
[/code]