Mybatis入门
一 、我的第一个mybatis程序
1、搭建环境
使用Idea配置maven工程
编写pom.xml文件
引入mysql驱动包,junit包,还有mybatis包
<?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>study</groupId>
<artifactId>mybatis</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>mybatis-day01</module>
<module>mybatis-day02</module>
<module>mybtis-day03</module>
</modules>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
!--maven导出资源依赖-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2、编写数据库
2.1、编写数据库
CREATE DATABASE `mybatis`;
USE mybatis;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE =INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'呐喊','123456'),
(2,'咆哮','123456'),
(3,'狂喊','123456')
2.2、IDEA连接数据库
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TJ505Bjs-1598337207973)(C:\Users\12920\AppData\Roaming\Typora\typora-user-images\image-20200821131833599.png)]
2.3、在resource下新建一个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>
<typeAliases>
<package name="com.heng.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<!--mapper注册-->
<mappers>
<mapper resource="com/heng/dao/UserMapper.xml"></mapper>
</mappers>
</configuration>
3、编写代码
包分类如下
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5Icq1cKt-1598337207975)(C:\Users\12920\AppData\Roaming\Typora\typora-user-images\image-20200821132045096.png)]
User类
package com.heng.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return this.pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String toString() {
return "User{id=" + this.id + ", name='" + this.name + '\'' + ", pwd='" + this.pwd + '\'' + '}';
}
}
UserDao接口
package com.heng.dao;
import com.heng.pojo.User;
import java.util.List;
public interface UserDao {
// 查询所有数
List<User> getUserList();
// 根据id查找
User getUserId(int id);
// 增加用户
int addUser(User user);
// 更新信息
int upDate(User user);
// 删除
int delete(int id);
}
UserDaoImpl
package com.heng.dao;
import com.heng.pojo.User;
import java.util.List;
public class UserDaoImpl implements UserDao {
public List<User> getUserList() {
return null;
}
@Override
public User getUserId(int id) {
return null;
}
@Override
public int addUser(User user) {
return 0;
}
@Override
public int upDate(User user) {
return 0;
}
@Override
public int delete(int id ) {
return 0;
}
}
Mybatis
package com.heng.util;
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 java.io.IOException;
import java.io.InputStream;
public class Mybatis {
public static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "Mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = (new SqlSessionFactoryBuilder()).build(inputStream);
} catch (IOException var3) {
var3.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
在dao包下面新建一个xml文件夹用来编写sql语句
<?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.heng.dao.UserDao">
<!-- 查找用户-->
<select id="getUserList" resultType="user">
select * from mybatis.user
</select>
<!-- 根据id查询-->
<select id="getUserId" resultType="user" parameterType="int">
select * from mybatis.user where id =#{id}
</select>
<insert id="addUser" parameterType="com.heng.pojo.User">
insert into mybatis.user(id, name, pwd) value (#{id},#{name},#{pwd})
</insert>
<update id="upDate" parameterType="com.heng.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id =#{id} ;
</update>
<delete id="delete" parameterType="com.heng.pojo.User">
delete from mybatis.user where id=#{id}
</delete>
</mapper>
4、编写测试类
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.heng.dao;
import com.heng.pojo.User;
import com.heng.util.Mybatis;
import java.util.Iterator;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class UserDaoTest {
public UserDaoTest() {
}
@Test
public void test() {
SqlSession sqlSession = Mybatis.getSqlSession();
UserDao userDao = (UserDao)sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
Iterator var4 = userList.iterator();
while(var4.hasNext()) {
User user = (User)var4.next();
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUserId() {
SqlSession sqlSession = Mybatis.getSqlSession();
UserDao mapper = (UserDao)sqlSession.getMapper(UserDao.class);
User user = mapper.getUserId(2);
System.out.println(user);
sqlSession.close();
}
@Test
public void addUser() {
SqlSession sqlSession = Mybatis.getSqlSession();
UserDao mapper = (UserDao)sqlSession.getMapper(UserDao.class);
int num = mapper.addUser(new User(4, "纸巾", "123465"));
if (num > 0) {
System.out.println("插入成功");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void upDate() {
SqlSession sqlSession = Mybatis.getSqlSession();
UserDao mapper = (UserDao)sqlSession.getMapper(UserDao.class);
mapper.upDate(new User(2, "冰淇淋", "123456"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void delete() {
SqlSession sqlSession = Mybatis.getSqlSession();
UserDao mapper = (UserDao)sqlSession.getMapper(UserDao.class);
mapper.delete(3);
sqlSession.commit();
sqlSession.close();
}
}
二、resultMap
1、字段名与属性名不一致时,通过结果集来返回结果
<resultMap id="UserMap" type="User">
<!--column是列名 peoperty是属性名-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserId" resultMap="UserMap">
select * from mybatis.user where id =#{id}
</select>
package com.heng.pojo;
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
1.1编写测试类,进行测试
@Test
public void getUserId(){
SqlSession sqlSession = Mybatis.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUserId(2);
System.out.println(user);
sqlSession.close();
}
三、多对一的处理
1、新建student表和teacher表插入数据
CREATE TABLE `teacher`(
`id` INT(20) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY(`id`)
)ENGINE =INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `student`(
`id` INT(20) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(20) DEFAULT NULL,
PRIMARY KEY(`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
)ENGINE =INNODB DEFAULT CHARSET=utf8;
INSERT INTO `teacher`(`id`,`name`) VALUES('1','秦老师');
INSERT INTO `student`(`id`,`name`,`tid`) VALUES('1','小明','1');
INSERT INTO `student`(`id`,`name`,`tid`) VALUES('2','小红','1');
INSERT INTO `student`(`id`,`name`,`tid`) VALUES('3','小李','1');
INSERT INTO `student`(`id`,`name`,`tid`) VALUES('4','小王','1');
INSERT INTO `student`(`id`,`name`,`tid`) VALUES('5','小秦','1');
2、编写代码
Student
package com.heng.pojo;
public class Student {
private int id;
private String name;
private Teacher teacher;
public Student() {
}
public Student(int id, String name, Teacher teacher) {
this.id = id;
this.name = name;
this.teacher = teacher;
}
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 Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", teacher=" + teacher +
'}';
}
}
Teacher
package com.heng.pojo;
public class Teacher {
private int id;
private String name;
public Teacher() {
}
public Teacher(int id, String name) {
this.id = id;
this.name = name;
}
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;
}
@Override
public String toString() {
return "TeacherMapper{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
package com.heng.dao;
import java.util.List;
import com.heng.pojo.*;
public interface StudentMapper {
public List<Student> getStudent();
}
UserMapper
package com.heng.dao;
import java.util.List;
import com.heng.pojo.*;
public interface StudentMapper {
public List<Student> getStudent();
}
<?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="dp.properties"></properties>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.heng.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- <mapper class="com/heng/dao/StudentMapper.xml"/>-->
<mapper class="com.heng.dao.StudentMapper"/>
<mapper class="com.heng.dao.TeacherMapper"/>
</mappers>
</configuratio
mybatis-mapper.xml
主要就是对前面的StudentMapper.xml和TeacherMapper.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="dp.properties"></properties>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.heng.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- <mapper class="com/heng/dao/StudentMapper.xml"/>-->
<mapper class="com.heng.dao.StudentMapper"/>
<mapper class="com.heng.dao.TeacherMapper"/>
</mappers>
</configuratio
编写StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.heng.dao.StudentMapper">
<!-- <select id="getStudent" resultType="Student">-->
<!-- select * from student-->
<!-- </select>-->
<select id="getStudent" resultMap="StudentTeacher">
select s.id sid,s.name sname,t.name tname
from student s ,teacher t
where s.tid=t.id;
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
</mapper>
编写测试类
@Test
public void getStudent() {
SqlSession sqlSession = Mybatis.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList= mapper.getStudent();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}
}
四、一对多的处理
TeacherMapper.xml编写
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.heng.dao.TeacherMapper">
<select id="getTeacher" resultMap="StudentTeacher">
select s.id sid,s.name sname,t.name tname,t.id,tid
from student s,teacher t
where s.tid =t.id and t.id=#{tid}
</select>
<resultMap id="StudentTeacher" type="Teacher">
<result property="id" column="tid" />
<result property="name" column="tname" />
<!-- 复杂的属性,我们需要单独处理 集合:collection 对象:associstion
javaType="" 指定属性的类型
OfTyp=""集合中的范型
-->
<collection property="student" ofType="student">
<result property="id" column="tid"/>
<result property="name" column="tname" />
<result property="tid" column="tid" />
</collection>
</resultMap>
</mapper>
测试类
@Test
public void getTeacher(){
SqlSession sqlSession = Mybatis.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
package com.heng.dao;
import com.heng.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface TeacherMapper {
//获取老师
//List<Teacher> getTeacher();
//获取学生指定的老师
Teacher getTeacher(@Param("tid") int id);
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6VSDNbIu-1598337207977)(C:\Users\12920\AppData\Roaming\Typora\typora-user-images\image-20200823131623803.png)]
五、动态SQL环境搭建
1、什么是动态SQL?动态SQL就是根据不同的条件生成不同的SQL语句
2、搭建环境
2.1、新建表
create table `blog`(
`id` varchar(50) not null comment '博客id',
`title` varchar(100) not null comment '博客标题',
`author` varchar(30) not null comment `创建时间`,
`create_time` datetime not null comment `创建时间`
`views` int(30) not null comment('浏览量')
)engine=InnoDB default charset=utf-8;
2.2、编写xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.heng.dao.BlogMapper">
<insert id="addUser" parameterType="blog">
insert into mybatis.blog(id, title, author, create_time, views) values (#{id},#{title},#{author},#{createtime},#{views})
</insert>
</mapper>
2.3、插入数据
import com.heng.dao.BlogMapper;
import com.heng.pojo.Blog;
import com.heng.util.IDutils;
import com.heng.util.Mybatis;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
public class MyTest {
@Test
public void getUser(){
SqlSession sqlSession = Mybatis.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDutils.getID());
blog.setTitle("java如此简单");
blog.setAuthor("呐喊");
blog.setCreatetime(new Date());
blog.setViews(9999);
mapper.addUser(blog);
blog.setId(IDutils.getID());
blog.setTitle("SpringBoot");
blog.setAuthor("呐喊");
mapper.addUser(blog);
blog.setId(IDutils.getID());
blog.setTitle("SpringMvc");
blog.setAuthor("呐喊");
mapper.addUser(blog);
blog.setId(IDutils.getID());
blog.setTitle("Spring");
blog.setAuthor("呐喊");
mapper.addUser(blog);
sqlSession.commit();
sqlSession.close();
}
}
2.4、关于id的问题,在工具类新建一个类
这样就可自动生成id
package com.heng.util;
import org.junit.Test;
import java.util.UUID;
public class IDutils {
public static String getID(){
return UUID.randomUUID().toString();
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PWWVP9u3-1598337207978)(C:\Users\12920\AppData\Roaming\Typora\typora-user-images\image-20200823135339487.png)]
3、动态sql之IF标签
xml文件编写sql语句
<!-- 和java里面的if判断差不多-->
<!-- where 1=1 是将所有的数据都查出来-->
<select id="queryBlog" parameterType="map" resultType="blog">
select * from mybatis.blog where 1= 1
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</select>
测试类
@Test
public void getBlog(){
SqlSession sqlSession = Mybatis.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","java如此简单");
map.put("author","呐喊");
List<Blog> blogs = mapper.queryBlog(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
4、where
where标签的好处就是,当你查询一个的时候,and会自动取消。
<select id="arrayBlog" parameterType="map" resultType="blog">
select * from blog
<where>
<if test="title != null">
title =#{title}
</if>
<if test="author != null">
and author =#{author}
</if>
</where>
</select>
测试类
@Test
public void getABlog() {
SqlSession sqlSession = Mybatis.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title", "java如此简单");
map.put("author", "呐喊");
List<Blog> blo = mapper.arrayBlog(map);
for (Blog blog : blo) {
System.out.println(blog);
}
}
5、choose when otherwise
在这个标签里面就是和java里面的swicht case循环一样,当首先匹配到一个就会优先筛选。
xml
<select id="listBlog" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
and title=#{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
测试类
@Test
public void getlisBlog(){
SqlSession sqlSession = Mybatis.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
//map.put("title","java如此简单");
map.put("author","呐喊");
map.put("views",9999);
List<Blog> blogs = mapper.listBlog(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
6、trim、where、set
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title=#{title},
</if>
<if test="author!=null">
author=#{author}
</if>
</set>
where id = #{id}
</updat
@Test
public void updateBlog(){
SqlSession sqlSession = Mybatis.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Java");
map.put("author","呐喊");
map.put("id","ce860ea9-6d54-4778-acc3-4bd2dcacdf50");
System.out.println( mapper.updateBlog(map));
sqlSession.commit();
sqlSession.close();
}