项目结构
数据库表
student_type 表
student 表
依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
实体类
Student 类
一个学生只有一个年级
package com.tmg.domain;
public class Student {
private int id;
private String name;
private int age;
private String email;
private Integer typeId;
private Type type;
public Integer getTypeId() {
return typeId;
}
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Student(int id, String name, int age, String email) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
}
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", email='" + email + '\'' +
", typeId=" + typeId +
// ", type=" + type +
'}';
}
}
Type 类
一个年级有多个学生,所以用 list
package com.tmg.domain;
import java.util.List;
public class Type {
private Integer id;
private String name;
private List<Student> students;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "Type{" +
"id=" + id +
", name='" + name + '\'' +
// ", students=" + students +
'}';
}
}
StudentDao
package com.tmg.dao;
import com.tmg.domain.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface StudentDao {
//多个参数的配置
void insertEmp( @Param("stuName") String name,
@Param("stuAge") int age, @Param("stuEmail") String email);
List<Student> selectByStudent(Student student);
void update(Student employee);
void update2(Student employee);
List<Student> selectByIds(@Param("ids") int []id);
// List<Student> selectById(int id);
List<Student> selectByTypeId(int id);
List<Student> selectAll();
}
TypeDao
package com.tmg.dao;
import com.tmg.domain.Type;
import java.util.List;
public interface TypeDao {
List<Type> selectAll();
Type selectById(Integer id);
}
mybatis-config.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>
<!-- dddd-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="ture"/><!--配置下划线转换为驼峰命名风格-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager><!--事务管理器-->
<dataSource type="POOLED"><!--数据源 POOLED代表池化-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="dao/StudentDao.xml"></mapper>
<mapper resource="dao/TypeDao.xml"></mapper>
</mappers>
</configuration>
TypeDao.xml
下列代码中:
1 resultMap 里面property对应实体类属性,column对应数据库字段名
2 主键用 id 标签 其他用result
3 关联查询(子查询和连接查询) 连接查询查一次
4 一个年级多个学生,所以用collection 如果一对一用association
<?xml version="1.0" encoding="UTF-8" ?>
<!--指定约束文件:定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序
mybatis-3-mapper.dtd 约束文件名称
-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tmg.dao.TypeDao">
<resultMap id="typeMap" type="com.tmg.domain.Type">
<id property="id" column="type_id"></id>
<result property="name" column="type_name"></result>
<!-- 连接查询-->
<!-- <collection property="students"-->
<!-- javaType="java.util.List" ofType="com.tmg.domain.Student">-->
<!-- <id property="id" column="stu_id" javaType="java.lang.Integer"></id>-->
<!-- <result property="name" column="stu_name"></result>-->
<!-- <result property="age" column="stu_age"></result>-->
<!-- <result property="email" column="stu_email"></result>-->
<!-- </collection>-->
<!-- 子查询-->
<collection property="students" column="type_id"
javaType="java.util.List" ofType="com.tmg.domain.Student"
select="com.tmg.dao.StudentDao.selectByTypeId">
</collection>
<!-- property 实体类中的属性名 column 子查询使用的字段 javaType 集合类型 ofType 集合里面的泛型类型-->
</resultMap>
<select id="selectAll" resultMap="typeMap">
select s.*,t.* from student s join student_type t on s.type_id=t.type_id
</select>
<select id="selectById" resultMap="typeMap">
select * from student_type where type_id=#{id}
</select>
</mapper>
StudentDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!--指定约束文件:定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序
mybatis-3-mapper.dtd 约束文件名称
-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--映射的命名空间 = 包名+接口类-->
<mapper namespace="com.tmg.dao.StudentDao">
<!--配置insert操作 id是方法名 parameterType是参数类型 #{属性名}用于读取对象的属性值-->
<!--#{}和${}的区别,#{}相当于PreparedStatement的占位符?提前编译,避免SQL注入 ${}是Statement字符串拼接,不能避免注入 -->
<!--获得最新的自增主键值 useGeneratedKeys=true keyProperty主键的属性-->
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into student( id,name,age,email) values (#{id},#{name},#{age},#{email});
</insert>
<!-- 问题:查询出的名称为多个单词的字段出现null值-->
<!-- 原因:数据库的字段单词以下划线分隔,Java的属性以驼峰命名,导致部分名称不一致无法实现映射-->
<select id="selectAll" resultMap="student">
select * from student
</select>
<resultMap id="student" type="com.tmg.domain.Student">
<!--配置主键 property是java属性名 column是表字段名-->
<id property="id" column="stu_id" javaType="java.lang.Integer"></id>
<!--普通字段-->
<result property="name" column="stu_name"></result>
<result property="age" column="stu_age"></result>
<result property="email" column="stu_email"></result>
<result property="typeId" column="type_id"></result>
<!-- <association property="type"-->
<!-- javaType="com.tmg.domain.Type">-->
<!-- <id property="id" column="type_id"></id>-->
<!-- <result property="name" column="type_name"></result>-->
<!-- </association>-->
<association property="type" column="type_id"
javaType="com.tmg.domain.Type"
select="com.tmg.dao.TypeDao.selectById">
</association>
</resultMap>
<!-- 动态sql-->
<sql id="mySelect">
select * from student
</sql>
<select id="selectByStudent" parameterType="com.tmg.domain.Student" resultType="com.tmg.domain.Student" resultMap="student">
<include refid="mySelect"></include>
<where>
<if test="name !=null">
stu_name like "%"#{name}"%"
</if>
<if test="age !=null and age!=0">
and stu_age=#{age}
</if>
<if test="email !=null">
and stu_email=#{email}
</if>
</where>
</select>
<update id="update">
update student
<set>
<if test="age !=null and age!=0">
stu_age=#{age},
</if>
<if test="email!=null">
stu_email=#{email},
</if>
<if test="name">
stu_name=#{name},
</if>
</set>
where stu_id=#{id};
</update>
<update id="update2">
update student
<trim prefix="set" suffixOverrides=",">
<if test="age !=null and age!=0">
stu_age=#{age},
</if>
<if test="email!=null">
stu_email=#{email},
</if>
<if test="name">
stu_name=#{name},
</if>
</trim>
where stu_id=#{id};
</update>
<select id="selectByIds" resultMap="student">
select s.*,t.* from student s join student_type t on s.type_id=t.type_id
where stu_id in
<foreach collection="ids" item="id" separator="," open="(" close=")" index="1">
#{id}
</foreach>
</select>
<select id="selectByTypeId" resultMap="student">
<include refid="mySelect"></include> where type_id=#{id}
</select>
</mapper>
TypeDaoText 测试类
package com.tmg.dao;
import com.tmg.domain.Type;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class TypeDaoText {
@Test
public void testselectAll() throws IOException {
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = build.openSession();
TypeDao mapper = sqlSession.getMapper(TypeDao.class);
List<Type> typeList = mapper.selectAll();
for (Type type : typeList) {
System.out.println(type);
}
}
@Test
public void testselectById() throws IOException {
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = build.openSession();
TypeDao mapper = sqlSession.getMapper(TypeDao.class);
Type type = mapper.selectById(1);
System.out.println(type);
}
}
StudentDaoText 测试类
package com.tmg.dao;
import com.tmg.domain.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class StudentDaoText {
@Test
public void testinsertEmp() throws IOException {
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = factory.openSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
mapper.insertEmp("tmg",18,"tmg@qq.com");
sqlSession.commit();
}
@Test
public void testselectByStudent() throws IOException {
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = build.openSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
// student.setName("z");
// student.setAge(18);
// student.setEmail("tmg@qq.com");
List<Student> students = mapper.selectByStudent(student);
for (Student student1 : students){
System.out.println(student1);
}
}
@Test
public void testupdate() throws IOException {
//创建会话工厂构建器
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
//创建会话
SqlSession sqlSession = build.openSession();
//获得Mapper对象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
// student.setName();
student.setId(1);
student.setAge(22);
mapper.update(student);
sqlSession.commit();
}
@Test
public void testupdate2() throws IOException {
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = build.openSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
student.setId(1);
student.setAge(44);
mapper.update2(student);
sqlSession.commit();
}
@Test
public void testselectByIds() throws IOException {
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = build.openSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
int []a={1};
List<Student> students = mapper.selectByIds(a);
for (Student student:students){
System.out.println(student);
System.out.println(student.getType());
}
}
@Test
public void testselectAll() throws IOException {
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = build.openSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
List<Student> students = mapper.selectAll();
for(Student student : students){
System.out.println(student);
System.out.println(student.getType());
}
}
}