文章目录
Mybatis笔记
什么是 MyBatis?
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
简单环境搭建
创建maven项目
maven导入依赖
这里加了lombok和junit
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
</dependency>
编写配置文件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 核心配置文件-->
<configuration>
<!--环境 可以切换 可以有多个环境-->
<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/{你的数据库名}?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="xxxxxx"/>
</dataSource>
</environment>
</environments>
<!--对于每一个Mapper.xml我们都需要加载,这里只有一个就只加载一个-->
<mappers>
<mapper resource="com/cai/mapper/UserMapper.xml"/>
</mappers>
</configuration>
编写工具类
由于每次配置mybatis-config.xml
都是相同的步骤,我们可以把配置的操作封装到工具类里
package com.cai.utils;
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;
/**
* @Description
* @Author Cai
* @Date 2021-03-23 20:20
*/
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {//静态代码块的作用是在最开始就加载xml配置文件
try {
//使用mybatis获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
实体类
编写实体类代码
package com.cai.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Description
* @Author Cai
* @Date 2021-03-23 20:31
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
Mapper接口
编写Mapper接口
这些方法和那些sql语句功能差不多的,如果只需要部分功能可以删掉一些
package com.cai.mapper;
import com.cai.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
int addUser(User user);
void updateUser(User user);
void updateUser2(Map<String, Object> map);//map操作
void deleteUser(int id);
}
Mapper.xml
和原来的UserDaoImpl
差不多,可以看成是Mapper这个接口的实现类,接口里每一个为实现的方法都需要实现
mapper的namespace的包名要写路径,即com.cai.mapper.UserMapper
-
id就是接口的方法名
-
parameterType就是参数类型
-
resultType就是返回类型,有时可以不写
如果类型是实体类,那需要在前面加上包名,例如:com.cai.pojo.User
<?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.cai.mapper.UserMapper">
<insert id="addUser" parameterType="com.cai.pojo.User">
insert into kuangshen.user(id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.cai.pojo.User">
update kuangshen.user
set name = #{name},
pwd = #{pwd}
where id = #{id};
</update>
<update id="updateUser2" parameterType="map">
update kuangshen.user
set name = #{n},
pwd = #{p}
where id = #{i};
</update>
<delete id="deleteUser">
delete from kuangshen.user where id = #{id}
</delete>
<select id="getUserList" resultType="com.cai.pojo.User">
select *
from kuangshen.user
</select>
<select id="getUserById" resultType="com.cai.pojo.User" parameterType="int">
select *
from kuangshen.user
where id = #{id}
</select>
</mapper>
可以回到上面mybatis-config.xml
那里,最后需要加载此文件
注册Mapper.xml
因为,一般在IDEA中,资源文件都是放在resources
的包下面才能识别,我们放在java文件目录下IDE是无法识别的,所以我们需要手动添加扫描路径
<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>
在pom.xml
中加上上面这段代码即可
编写测试类
使用junit进行测试
对每一个方法进行测试,效果和我们的sql差不多
sqlSession需要close,官网推荐使用try资源释放
注意:增删改要提交事务sqlSession.commit();
否则无法生效
package com.cai.mapper;
import com.cai.pojo.User;
import com.cai.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserMapperTest {
@Test
public void testGetUserList() {
//获得SqlSession对象,可以自动关闭资源,无需close
try (SqlSession sqlSession = MybatisUtils.getSession()) {
//方式一,getUserList
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
//方式二:
// List<User> userList = sqlSession.selectList("com.cai.mapper.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
}
}
@Test
public void testGetUserById() {
try (SqlSession sqlSession = MybatisUtils.getSession()) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
}
}
@Test
public void addUser() {
try (SqlSession sqlSession = MybatisUtils.getSession()) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.addUser(new User(4, "cwj2", "818181"));
if (res > 0) {
System.out.println("插入成功!");
}
sqlSession.commit();
}
}
@Test
public void updateUser() {
try (SqlSession sqlSession = MybatisUtils.getSession()) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(2, "zzz", "818181"));
sqlSession.commit();
}
}
/**
* map参数的应用
*/
@Test
public void updateUser2() {
try (SqlSession sqlSession = MybatisUtils.getSession()) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("n", "test");
map.put("i", 2);
mapper.updateUser2(map);
sqlSession.commit();
}
}
@Test
public void deleteUser() {
try (SqlSession sqlSession = MybatisUtils.getSession()) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
sqlSession.commit();
}
}
}
Map的使用
Map传递参数,直接在sql中取出key即可
parameterType="map"
对象传递参数,直接在sql中取出对象的属性即可
parameterType="Object"
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用Map,或者注解
参考自官方文档:https://mybatis.org/mybatis-3/zh/index.html与狂神说视频