hibernate中的多对多关系
在hibernate中,多对多关系指的是一个实体可以与多个另一个实体实例相关联,反之亦然。为了实现这种关系,通常需要一个中间表来存储两者之间的关联信息。
多对多关系的示例代码
实体类定义
假设我们有两个实体:student 和 course,一个学生可以选修多门课程,一门课程也可以有多个学生。
student类
package com.example.domain;
import javax.persistence.*;
import java.util.hashset;
import java.util.set;
@entity
@table(name = "student")
public class student {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
@column(name = "name")
private string name;
@manytomany(cascade = { cascadetype.all })
@jointable(
name = "student_course",
joincolumns = { @joincolumn(name = "student_id") },
inversejoincolumns = { @joincolumn(name = "course_id") }
)
private set<course> courses = new hashset<>();
public student() {}
public student(string name) {
this.name = name;
}
// getters 和 setters
public long getid() {
return id;
}
public void setid(long id) {
this.id = id;
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public set<course> getcourses() {
return courses;
}
public void setcourses(set<course> courses) {
this.courses = courses;
}
}
course类
package com.example.domain;
import javax.persistence.*;
import java.util.hashset;
import java.util.set;
@entity
@table(name = "course")
public class course {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
@column(name = "name")
private string name;
@manytomany(mappedby = "courses")
private set<student> students = new hashset<>();
public course() {}
public course(string name) {
this.name = name;
}
// getters 和 setters
public long getid() {
return id;
}
public void setid(long id) {
this.id = id;
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public set<student> getstudents() {
return students;
}
public void setstudents(set<student> students) {
this.students = students;
}
}
hibernate配置文件hibernate.cfg.xml
<!doctype hibernate-configuration public
"-//hibernate/hibernate configuration dtd 3.0//en"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接配置 -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<!-- hibernate 属性配置 -->
<property name="hibernate.dialect">org.hibernate.dialect.mysqldialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 映射类 -->
<mapping class="com.example.domain.student"/>
<mapping class="com.example.domain.course"/>
</session-factory>
</hibernate-configuration>
hibernateutil类
import org.hibernate.sessionfactory;
import org.hibernate.cfg.configuration;
public class hibernateutil {
private static final sessionfactory sessionfactory;
static {
try {
// 从配置文件创建sessionfactory
sessionfactory = new configuration().configure("hibernate.cfg.xml").buildsessionfactory();
} catch (throwable ex) {
// 记录启动失败的错误
system.err.println("initial sessionfactory creation failed." + ex);
throw new exceptionininitializererror(ex);
}
}
public static sessionfactory getsessionfactory() {
return sessionfactory;
}
}
插入示例数据
import org.hibernate.session;
import org.hibernate.sessionfactory;
import org.hibernate.transaction;
public class hibernateinsertdata {
public static void main(string[] args) {
// 获取sessionfactory
sessionfactory sessionfactory = hibernateutil.getsessionfactory();
// 插入示例数据
insertsampledata(sessionfactory);
// 关闭sessionfactory
sessionfactory.close();
}
private static void insertsampledata(sessionfactory sessionfactory) {
session session = sessionfactory.opensession();
transaction transaction = session.begintransaction();
try {
// 创建学生
student student1 = new student("john doe");
student student2 = new student("jane doe");
// 创建课程
course course1 = new course("mathematics");
course course2 = new course("history");
// 建立多对多关系
student1.getcourses().add(course1);
student1.getcourses().add(course2);
student2.getcourses().add(course1);
student2.getcourses().add(course2);
course1.getstudents().add(student1);
course1.getstudents().add(student2);
course2.getstudents().add(student1);
course2.getstudents().add(student2);
// 保存数据
session.save(student1);
session.save(student2);
transaction.commit();
system.out.println("inserted sample data");
} catch (exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printstacktrace();
} finally {
if (session != null) {
session.close();
}
}
}
}
查询示例数据
import org.hibernate.session;
import org.hibernate.sessionfactory;
public class hibernatequeryexample {
public static void main(string[] args) {
// 获取sessionfactory
sessionfactory sessionfactory = hibernateutil.getsessionfactory();
// 查询示例数据
querysampledata(sessionfactory);
// 关闭sessionfactory
sessionfactory.close();
}
private static void querysampledata(sessionfactory sessionfactory) {
session session = sessionfactory.opensession();
try {
// 查询所有学生
list<student> students = session.createquery("from student", student.class).list();
for (student student : students) {
system.out.println("student name: " + student.getname());
for (course course : student.getcourses()) {
system.out.println(" enrolled in: " + course.getname());
}
}
// 查询所有课程
list<course> courses = session.createquery("from course", course.class).list();
for (course course : courses) {
system.out.println("course name: " + course.getname());
for (student student : course.getstudents()) {
system.out.println(" student: " + student.getname());
}
}
} catch (exception e) {
e.printstacktrace();
} finally {
if (session != null) {
session.close();
}
}
}
}
多对多关系的详细解释
实体类定义:
student类和course类通过@manytomany注解来定义多对多的关系。student类中使用@jointable注解来定义中间表,指定了关联的学生和课程的外键。course类中使用mappedby属性来指定关系维护由student类中的courses属性来负责。
hibernate配置文件:
- 标准的hibernate配置文件,用于数据库连接和映射类的配置。
hibernateutil类:
- 一个实用类,用来创建和返回
sessionfactory实例。
- 一个实用类,用来创建和返回
插入示例数据:
- 创建
student和course对象,并建立多对多关系。 - 保存数据到数据库中。
- 创建
查询示例数据:
- 查询所有学生和他们所选修的课程,以及所有课程和选修这些课程的学生。
到此这篇关于hibernate处理多对多关系的实现示例的文章就介绍到这了,更多相关hibernate 多对多内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论