Hibernate03_多对多
一门课程可以被多个学生选择,一个学生可以选择多门课程。
学生和课程是多对多关系。
在数据库中,学生和课程都是主表,中间表为从表。主表与中间表是一对多关系。
t_course表
account_course中间表
package com.blu.entity;
import java.util.Set;
import lombok.Data;
@Data
public class Account {
private Integer id;
private String name;
private Set<Course> courses;
}
package com.blu.entity;
import java.util.Set;
import lombok.Data;
@Data
public class Course {
private Integer id;
private String name;
private Set<Account> accounts;
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.blu.entity.Account" table="t_account">
<id name="id" type="java.lang.Integer">
<column name="id"></column>
<generator class="identity"></generator>
</id>
<property name="name" type="java.lang.String">
<column name="name"></column>
</property>
<set name="courses" table="account_course">
<key column="aid"></key>
<many-to-many class="com.blu.entity.Course" column="cid"></many-to-many>
</set>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.blu.entity.Course" table="t_course">
<id name="id" type="java.lang.Integer">
<column name="id"></column>
<generator class="identity"></generator>
</id>
<property name="name" type="java.lang.String">
<column name="name"></column>
</property>
<set name="accounts" table="account_course">
<key column="cid"></key>
<many-to-many class="com.blu.entity.Account" column="aid"></many-to-many>
</set>
</class>
</hibernate-mapping>
<mapping resource="com/blu/entity/Account.hbm.xml"></mapping>
<mapping resource="com/blu/entity/Course.hbm.xml"></mapping>
package com.blu.test;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.blu.entity.Account;
import com.blu.entity.Course;
public class Test {
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Course course = new Course();
course.setName("Java");
Account account = new Account();
account.setName("张三");
Set<Course> courses = new HashSet<Course>();
courses.add(course);
account.setCourses(courses);
session.save(course);
session.save(account);
session.beginTransaction().commit();
session.close();
}
}
Hibernate:
insert
into
t_course
(name)
values
(?)
Hibernate:
insert
into
t_account
(name)
values
(?)
Hibernate:
insert
into
account_course
(aid, cid)
values
(?, ?)
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blucoding.blog.csdn.net/article/details/107783746
内容来源于网络,如有侵权,请联系作者删除!