多对多保存实例(保存学生)
项目目录结构(maven):
多对多保存学生灵魂之处解析:
StudentMapper.xml
不保存主键的运行结果:
新增学生的id为0,tea_id应该是正常的,只是因为我之前代码写错了,主要看学生id会为0;
(所有表id都设置了自动递增)
创建表t_stu:
创建表t_teacher:
创建关系表t_stu_tea:
在Maven配置文件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>com.xiongluoluo</groupId>
<artifactId>manytomany</artifactId>
<version>1.0.0</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--日志包-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
创建实体类Student:
package com.xiongluoluo.bean;
import lombok.*;
import java.util.List;
/**
* Created by Administrator on 2019/12/28 0028.
*/
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private List<Teacher> teacherList;
/*这里new不new对象都行*/
}
创建实体类Teacher:
package com.xiongluoluo.bean;
import lombok.*;
/**
* Created by Administrator on 2019/12/28 0028.
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
private int id;
private String name;
}
创建mybatis配置文件Mybatis.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<!--这里用的是resource属性,导入外部properties文件-->
<typeAliases>
<package name="com.xiongluoluo.bean"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driverClassName}"/>
<!--这里是driver-->
<!--driverClassName是properties文件中的变量,通过${}取其对应的支持-->
<!--下面同理-->
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/xiongluoluo/mapper/StudentMapper.xml"/>
<!--这里是斜线(因为是目录),不是点,不是点,不是点,你能不能不要在一个错误上躺平,每天忘提交事务,每天写...,唉-->
<!--Mybatis的配置文件,也就是这个文件,是程序的入口.我们配置的mapper文件如果不在这里注册
那么程序是读不到的.所以一定别忘记在这里添加.
这里用的也是resource属性,引入外部的mapper.xml属性-->
</mappers>
</configuration>
db.properties文件:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///mydb1228
username=root
password=1234
log4j.properties文件:
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.com.xiongluoluo.mapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
创建StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xiongluoluo.mapper.StudentMapper">
<!--多对多保存学生,先保存学生,再保存关系,一定要保存自动生长的主键-->
<insert id="insertStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into t_stu(name) values(#{name})
</insert>
<insert id="insertRelation">
insert into t_stu_tea(stu_id,tea_id) values(#{stuId},#{teaId})
</insert>
</mapper>
创建StudentMapper.java:
package com.xiongluoluo.mapper;
import com.xiongluoluo.bean.Student;
import org.apache.ibatis.annotations.Param;
/**
* Created by Administrator on 2019/12/28 0028.
*/
public interface StudentMapper {
/*保存学生*/
public void insertStudent(Student student);
/*保存关系,使用注解传参*/
public void insertRelation(@Param("stuId")Integer stuId,@Param("teaId")Integer teaId);
}
创建StudentService.java:
package com.xiongluoluo.service;
import com.xiongluoluo.bean.Student;
/**
* Created by Administrator on 2019/12/28 0028.
*/
public interface StudentService {
/*保存学生*/
public void saveStudent(Student student);
}
创建StudentServiceImpl.java:
package com.xiongluoluo.service.impl;
import com.xiongluoluo.bean.Student;
import com.xiongluoluo.bean.Teacher;
import com.xiongluoluo.mapper.StudentMapper;
import com.xiongluoluo.service.StudentService;
import com.xiongluoluo.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
/**
* Created by Administrator on 2019/12/28 0028.
*/
public class StudentServiceImpl implements StudentService {
public void saveStudent(Student student) {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.insertStudent(student);//保存学生
for(Teacher teacher : student.getTeacherList()){
mapper.insertRelation(student.getId(),teacher.getId());
}//保存关系
sqlSession.commit();
sqlSession.close();
//查询可以不提交事务,增删改一定要记得提交事务
}
}
创建测试类:
package com.xiongluoluo.test;
import com.xiongluoluo.bean.Student;
import com.xiongluoluo.bean.Teacher;
import com.xiongluoluo.service.StudentService;
import com.xiongluoluo.service.impl.StudentServiceImpl;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2019/12/28 0028.
*/
public class MybatisTest {
@Test
public void test1(){
Teacher teacher = new Teacher();
teacher.setId(1);
Teacher teacher1 = new Teacher();
teacher1.setId(3);
List<Teacher> teachers = new ArrayList<Teacher>();
teachers.add(teacher);
teachers.add(teacher1);
Student student = new Student();
student.setName("余洋");
student.setTeacherList(teachers);
StudentService studentService = new StudentServiceImpl();
studentService.saveStudent(student);
}
}