MyBatis使用手册

本文最后更新于:2 年前

R-C

MyBatis使用配置

简介

基础搭建

Maven导入依赖

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>

编写MyBatis核心配置文件

resources 下创建mybatis-config.xml 配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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">
<!--5版本的com.mysql.jdbc.Driver;8版本的com.mysql.cj.jdbc.Driver -->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="******"/>
</dataSource>
</environment>
</environments>

<!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!-->
<mappers>
<mapper resource="com/ajie/dao/UserMapper.xml"/>
</mappers>
</configuration>

编写MyBatis工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//默认在resources路径下
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取SqlSession连接
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}

创建实体类

1
2
3
4
5
6
7
8
9
10
public class User {
private type name;
...
{//构造,有参,无参
//set/get
//toString()
}
//或者LomBok的@Date
}

编写Mapper接口类

1
2
3
4
5
6
7
import com.ajie.pojo.User;
import java.util.List;
public interface UserMapper {
//接口方法
List<User> selectUser();
}

编写Mapper.xml配置文件

namespace 十分重要,不能写错!

1
2
3
4
5
6
7
8
9
10
<?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.ajie.dao.UserMapper">
<select id="selectUser" resultType="com.ajie.pojo.User">
<!--写SQL语句-->
select * from user
</select>
</mapper>
  • id
    • 命名空间中唯一的标识符
    • 接口中的方法名与映射文件中的SQL语句ID 一一对应
  • parameterType
    • 传入SQL语句的参数类型 。【万能的Map,可以多尝试使用】
  • resultType
    • SQL语句返回值类型。【完整的类名或者别名】

参数传递

思路一:直接在方法中传递参数

  1. 在接口方法的参数前加 @Param属性
  2. Sql语句编写的时候,直接取@Param中设置的值即可,不需要单独设置参数类型
1
2
3
4
5
6
7
//通过密码和名字查询用户
User selectUserByNP(@Param("username") String username,@Param("pwd") String pwd);
/*
<select id="selectUserByNP" resultType="com.ajie.pojo.User">
select * from user where name = #{username} and pwd = #{pwd}
</select>
*/

思路二:使用万能的Map

  1. 在接口方法中,参数直接传递Map;

    1
    User selectUserByNP2(Map<String,Object> map);
  2. 编写sql语句的时候,需要传递参数类型,参数类型为map

    1
    2
    3
    <select id="selectUserByNP2" parameterType="map" resultType="com.ajie.pojo.User">
    select * from user where name = #{username} and pwd = #{pwd}
    </select>
  3. 在使用方法的时候,Map的 key 为 sql中取的值即可,没有顺序要求!

    1
    2
    3
    4
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("username","小明");
    map.put("pwd","123456");
    User user = mapper.selectUserByNP2(map);

    事务提交

    增、删、改操作需要提交事务!

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @Test
    public void testAddUser() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
    User user = new User(5,"王五","zxcvbn");
    int i = mapper.addUser(user);
    System.out.println(i);
    session.commit(); //提交事务,重点!不写的话不会提交到数据库
    session.close();
    }

    标签

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    List<User> getUserLike(String value);

    //查询全部用户
    List<User> getUserList();

    //根据ID查询用户
    User getUserById(int id);

    //User getUserById2(Map<String,Object> map);

    //insert一个用户
    int addUser(User user);

    //万能的Map
    //int addUser2(Map<String,Object> map);

    //修改用户
    int updateUser(User user);

    //删除一个用户
    int deleteUser(int id);
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
     <select id="getUserLike" resultType="com.ajie.pojo.User">
    select * from mybatis.user where name like "%"#{value}"%"
    </select>

    <!--select查询语句-->
    <select id="getUserList" resultType="com.ajie.pojo.User">
    select * from mybatis.user
    </select>

    <select id="getUserById" resultType="com.ajie.pojo.User">
    select * from mybatis.user where id = #{id}
    </select>

    <!--对象中的属性,可以直接取出来-->
    <insert id="addUser" parameterType="com.ajie.pojo.User">
    insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
    </insert>

    <update id="updateUser" parameterType="com.ajie.pojo.User">
    update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id} ;
    </update>

    <delete id="deleteUser" parameterType="int">
    delete from mybatis.user where id = #{id};
    </delete>

    Like语句

    1
    2
    3
    4
    5
    6
    7
    String wildcardname = “%smi%”;
    List<name> names = mapper.selectlike(wildcardname);

    <select id=”selectlike”>
    select * from foo where bar like #{value}
    </select>

    小结

    • 所有的增删改操作都需要提交事务!
    • 接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!
    • 有时候根据业务的需求,可以考虑使用map传递参数!
    • 为了规范操作,在SQL的配置文件中,尽量将Parameter参数和resultType都写上!

编写测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MyTest {
@Test
public void selectUser() {
SqlSession session = MybatisUtils.getSession();
//方法一:
//List<User> users = session.selectList("com.ajie.mapper.UserMapper.selectUser");
//方法二:
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.selectUser();
for (User user: users){
System.out.println(user);
}
session.close();
}
}

如果参数过多,我们可以考虑直接使用Map实现,如果参数比较少,直接传递参数即可


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!