本次使用JPA实现多对多的简单案例,学生和课程之间的关系为多对多关系,所以本次使用案例选择这个来做。
环境搭建及基本包创建代码编写
1.新建基本的maven工程命名为jpa-CourseToStudent。并在pom.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>cn.lut</groupId>
<artifactId>jpa-CourseToStudent</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<hibernate.version>5.4.20.Final</hibernate.version>
<mysql.version>8.0.21</mysql.version>
<c3p0.version>0.9.5.5</c3p0.version>
<slf4j.version>1.7.30</slf4j.version>
<spring.version>5.2.7.RELEASE</spring.version>
</properties>
<dependencies>
<!--junit单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--log日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--spring beg-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring对orm框架的支持包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!--hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<!--c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.el/javax.el-api -->
<!--使用spring data jpa 必须导入的el-->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>
</dependencies>
</project>
2.在src-main-java包下新建包cn.lut.dao和cn.lut.domain包用于创建实体类对象和相应的持久层接口。
①在domain包下新建Student和Course实体类
Student.java代码如下:
package cn.lut.domain;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "stu_id")
private Long stuId;
@Column(name = "stu_name")
private String stuName;
@Column(name = "stu_age")
private Integer stuAge;
@Column(name = "major")
private String major;
/*配置学生到课程的多对多关系
* 配置多对多的映射关系:
* 1声明表关系配置
* 2配置中间表(包含两个外键)
* */
@ManyToMany(targetEntity = Course.class,cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinTable(name = "sys_stu_cou",//中间表的名称
//joinColumns当前对象在中间表中的外键
joinColumns = {@JoinColumn(name = "sys_stu_id",referencedColumnName = "stu_id")},
//inverseJoinColumns对方对象在中间表中的外键
inverseJoinColumns = {@JoinColumn(name = "sys_cou_id",referencedColumnName = "cou_id")}
)
private Set<Course> courses=new HashSet<Course>();
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", stuName='" + stuName + '\'' +
", stuAge=" + stuAge +
", major='" + major + '\'' +
'}';
}
public Long getStuId() {
return stuId;
}
public void setStuId(Long stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Integer getStuAge() {
return stuAge;
}
public void setStuAge(Integer stuAge) {
this.stuAge = stuAge;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}
Course.java中代码如下:
package cn.lut.domain;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "cou_id")
private Long couId;
@Column(name = "cou_name")
private String couName;
@ManyToMany(mappedBy = "courses",fetch = FetchType.LAZY)
private Set<Student> students=new HashSet<Student>();
@Override
public String toString() {
return "Course{" +
"couId=" + couId +
", couName='" + couName + '\'' +
'}';
}
public Long getCouId() {
return couId;
}
public void setCouId(Long couId) {
this.couId = couId;
}
public String getCouName() {
return couName;
}
public void setCouName(String couName) {
this.couName = couName;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
②在dao包下新建持久层接口
IStudentDao.java代码如下:
package cn.lut.dao;
import cn.lut.domain.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface IStudentDao extends JpaRepository<Student,Long>, JpaSpecificationExecutor<Student> {
}
IcourseDao.java中代码如下:
package cn.lut.dao;
import cn.lut.domain.Course;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface ICourseDao extends JpaSpecificationExecutor<Course>, JpaRepository<Course,Long> {
}
3.创建resources资源包下的配置文件applicationContext.xml文件其中添加配置。
applicationContext.xml中的代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--spring和spring data jpa的配置-->
<!--创建entityManagerFactory对象交给spring容器管理-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--自动扫描实体类的包-->
<property name="packagesToScan" value="cn.lut.domain"/>
<!--jap的实现方式-->
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
<!--jpa的供应商适配器-->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false"/><!--自动创建数据库表-->
<property name="database" value="MYSQL"/><!--数据库类型-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/><!--数据库方言:支持的特有语法-->
<property name="showSql" value="true"/>
</bean>
</property>
<!--注入jpa的配置信息,加载jpa的基本配置信息,和jpa实现方式的配置信息-->
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!--jpa方言高级特性-->
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<!--创建数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
<property name="jdbcUrl" value="jdbc:mysql:///jpa?serverTimezone=UTC"></property>
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
</bean>
<!--整合spring data JPA-->
<jpa:repositories base-package="cn.lut.dao" transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<!--声明式事务-->
<!--配置注解包扫描-->
<context:component-scan base-package="cn.lut"></context:component-scan>
</beans>
4.创建测试类
CouToStuTest.java
package cn.lut.test;
import cn.lut.dao.ICourseDao;
import cn.lut.dao.IStudentDao;
import cn.lut.domain.Course;
import cn.lut.domain.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Set;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class CouToStuTest {
@Autowired
private IStudentDao studentDao;
@Autowired
private ICourseDao courseDao;
@Test
@Transactional
@Rollback(value = false)
public void testAdd(){
Student stu=new Student();
stu.setStuName("jack");
Course cou=new Course();
cou.setCouName("English");
//配置学生到课程之间的关系
stu.getCourses().add(cou);
//配置课程到学生之间的关系
cou.getStudents().add(stu);
studentDao.save(stu);
}
@Test
@Transactional
@Rollback(value = false)
public void testDel(){
//查询1号学生
Student student=studentDao.getOne(1l);
System.out.println(student);
Set<Course> courses = student.getCourses();
for(Course c:courses){
System.out.println(c);
}
//删除一号学生
//studentDao.delete(student);
}
}
注意在第一次测试存储时配置文件中的配置jpa实现方式的配置为:
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
测试删除时修改为:
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
创建完成后的工程结构如下: