0
点赞
收藏
分享

微信扫一扫

Hibernate+maven+mysql处理多对多映射

一 代码

1.1项目结构

Hibernate+maven+mysql处理多对多映射_java

1.2pom.xml



<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>Hibernate-Test</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.7</version>
<configuration>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8888</port>
<maxIdleTime>30000</maxIdleTime>
</connector>
</connectors>
<webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
<contextPath>/</contextPath>
</configuration>
</plugin>
</plugins>
<!--把xml文件也编译-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>

<!-- 添加Hibernate依赖 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.5.Final</version>
</dependency>

<!-- 添加Log4J依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.6.4</version>
</dependency>

<!-- 添加javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.11.0.GA</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.8</version>
</dependency>
</dependencies>

</project>


1.3hibernate.cfg.xml



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/cars</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!--显示生成的sql语句-->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 禁用了javaEE6的bean-validate -->
<property name="javax.persistence.validation.mode">none</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<!-- 即可通过getCurrentSession 获取线程唯一的session -->
<property name="current_session_context_class">thread</property>

<!--在数据库中自动创建表-->
<!--<property name="hbm2ddl.auto">update</property>-->
<!-- 指定ddl的生成方式 -->
<!--<property name="hibernate.hbm2ddl.auto">create</property>-->

<mapping resource="com/test/model/PersonEntity.hbm.xml"/>

<mapping class="com.test.model.Student"/>
<mapping class="com.test.model.Teacher"/>
<mapping class="com.test.model.TeacherStudent"/>
</session-factory>
</hibernate-configuration>


1.4HibernateUtil



package com.test.utils;

/**
* @Author yqq
* @Date 2021/6/22 0:36
* @Version 1.0
*/
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
/** ThreadLocal Session Map */
public static final ThreadLocal<Session> SESSIONMAP = new ThreadLocal<Session>();
private static final SessionFactory sessionFactory;
private static final Logger LOGGER = Logger.getLogger(HibernateUtil.class);

static {
try {
LOGGER.debug("HibernateUti.static - loading cofig");
sessionFactory = new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory();
LOGGER.debug("HibernateUtil.static - end");
} catch (Throwable ex) {
ex.printStackTrace();
LOGGER.error("HibernateUti error : ExceptionInInitializerError");
throw new ExceptionInInitializerError(ex);
}
}

private HibernateUtil() {

}

public static Session getSession() throws HibernateException {
Session session = SESSIONMAP.get();

if(session == null) {
session = sessionFactory.openSession();
SESSIONMAP.set(session);
}

return session;
}

public static void closeSession() throws HibernateException {
Session session = SESSIONMAP.get();
SESSIONMAP.set(null);

if(session != null) {
session.close();
}
}

}


1.5Student



package com.test.model;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;

/**
* @Author yqq
* @Date 2021/6/24 22:37
* @Version 1.0
*/
@Entity
@Table(name = "T_STUDENT")
@SequenceGenerator(name = "SEQ_STUDENT", sequenceName = "SEQ_STUDENT")
public class Student implements Serializable {
private static final long serialVersionUID = 2524659555729848644L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "SEQ_STUDENT")
@Column(name = "ID", nullable = false, precision = 22, scale = 0)
private Long id;
@Column(name = "NAME")
private String name;
@Temporal(TemporalType.DATE)
@Column(name = "BIRTHDAY")
private Date birthday;
@Column(name = "sex")
private int sex;
@Column(name = "address")
private String address;
@OneToMany(mappedBy="student",cascade=CascadeType.ALL)
private Set<TeacherStudent> teacherStudentList;

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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}

public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}

public Set<TeacherStudent> getTeacherStudentList() {
return teacherStudentList;
}
public void setTeacherStudentList(Set<TeacherStudent> teacherStudentList) {
this.teacherStudentList = teacherStudentList;
}
}


1.6Teacher



package com.test.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;

/**
* @Author yqq
* @Date 2021/6/24 22:38
* @Version 1.0
*/
@Entity
@Table(name = "T_TEACHER")
@SequenceGenerator(name = "SEQ_TEACHER", sequenceName = "SEQ_TEACHER")
public class Teacher implements Serializable {
private static final long serialVersionUID = 2297316923535111793L;
private Long id;
private String name;
private int sex;
private Set<TeacherStudent> teacherStudentList;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "SEQ_TEACHER")
@Column(name = "ID", nullable = false, precision = 22, scale = 0)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "sex")
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
@OneToMany(mappedBy = "teacher",cascade=CascadeType.ALL)
public Set<TeacherStudent> getTeacherStudentList() {
return teacherStudentList;
}
public void setTeacherStudentList(Set<TeacherStudent> teacherStudentList) {
this.teacherStudentList = teacherStudentList;
}
}


1.7TeacherStudent



package com.test.model;
import javax.persistence.*;
import java.io.Serializable;

/**
* @Author yqq
* @Date 2021/6/24 22:39
* @Version 1.0
*/
@Entity
@Table(name = "T_TEACHERSTUDENT")
@SequenceGenerator(name = "SEQ_TEACHERSTUDENT", sequenceName = "SEQ_TEACHERSTUDENT")
public class TeacherStudent implements Serializable {
private Long id;
private Student student;
private Teacher teacher;
private String note1;
private String note2;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "SEQ_TEACHERSTUDENT")
@Column(name = "ID", nullable = false, precision = 22, scale = 0)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "note11")
public String getNote1() {
return note1;
}
public void setNote1(String note1) {
this.note1 = note1;
}
@Column(name = "note22")
public String getNote2() {
return note2;
}
public void setNote2(String note2) {
this.note2 = note2;
}
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "student_id", unique = true)
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
@ManyToOne
@JoinColumn(name = "teacher_id", unique = true)
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}


1.8ModelTest



@Test
public void tests(){
Session session = HibernateUtil.getSession();
session.beginTransaction();
Student s = new Student();
s.setName("小猪");
Teacher t = new Teacher();
t.setName("小李");
TeacherStudent ts=new TeacherStudent();
ts.setStudent(s);
ts.setTeacher(t);
ts.setNote1("以呀呀!!!");
ts.setNote2("哎哎呀");
session.save(s);
session.save(t);
session.save(ts);
session.getTransaction().commit();
HibernateUtil.closeSession();
}


二 数据脚本

2.1从表

注意:该表两个外键(student_id,teacher_id)分别指向相应表的ID

DROP TABLE IF EXISTS `t_teacherstudent`;
CREATE TABLE `t_teacherstudent` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`note11` varchar(255) NOT NULL,
`note22` varchar(255) NOT NULL,
`student_id` int(11) DEFAULT NULL,
`teacher_id` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `sid` (`student_id`),
KEY `tid` (`teacher_id`),
CONSTRAINT `sid` FOREIGN KEY (`student_id`) REFERENCES `t_student` (`ID`),
CONSTRAINT `tid` FOREIGN KEY (`teacher_id`) REFERENCES `t_teacher` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;


2.2主表1



DROP TABLE IF EXISTS `t_teacher`;
CREATE TABLE `t_teacher` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`sex` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;


2.3主表2



DROP TABLE IF EXISTS `t_student`;
CREATE TABLE `t_student` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`birthday` varchar(255) DEFAULT NULL,
`sex` int(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;



举报

相关推荐

0 条评论