Mybatis的使用

首先,我们需要先创建一个Maven项目,可参考我之前编写的Maven项目的创建

1.导入相关依赖包

<!-- Mybatis核心 -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.7</version>
</dependency>
<!-- junit测试 -->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>
<!-- MySQL驱动 -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.3</version>
</dependency>

2.创建MyBatis的核心配置文件

先配置一个数据库配置文件db.properties,配置文件存放的位置是src/main/resources目录下

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.111.131:3306/mybatis?characterEncoding=UTF-8
username=root
password=123456

然后创建MyBatis核心配置文件,习惯上命名为mybatis-config.xml,核心配置文件存放的位置是src/main/resources目录下

<?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"/>

    <settings>
        <!--实体类驼峰命名与数据库_命名映射开启-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!--设置连接数据库的环境-->
    <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>
    </environments>
    <!--引入映射文件-->
    <mappers>
        <mapper resource="mappers/UserMapper.xml"/>
    </mappers>
</configuration>

3.创建实体类

public class User {

    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String sex;
    private String email;
   
    //get、set、toString、有参无参构造也要记得配置上,这里省略掉了
}

4.创建Mapper接口

MyBatis中的mapper接口相当于以前的dao。但是区别在于,mapper仅仅是接口,我们不需要提供实现类。

public interface UserMapper {
    /**
     * 添加用户信息
     */
    int insertUser(User user);

    // 假设我们实体类或数据库中的表,字段,参数过多,我们应该考虑使用Map,使用Map甚至可以不需要实体类
    int inserUser2(Map<String,Object> map);

    /**
     * 查看所有用户信息
     */
    List<User> getAllUser();

    /**
     * 模糊查询用户信息
     */
    List<User> getAllUser2(String value);

    /**
     * 分页查询
     */
    List<User> getUserByLimit(Map<String,Integer> map);

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

5.创建MyBatis的映射文件

命名规则:表所对应的实体类的类名+Mapper.xml

MyBatis映射文件存放的位置是src/main/resources/mappers目录下

注:mapper接口的全类名和映射文件中的命名空间(namespace)保持一致。

1.id就是对应的namespace中的方法

2.resultType为sql执行的返回值

3.parameterType为参数类型

<?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.chen.mybatis.mapper.UserMapper">

    <insert id="insertUser" parameterType="com.chen.mybatis.pojo.User" >
        insert into t_user values(#{id},#{username},#{password},#{age},#{sex},#{email})
    </insert>

    <insert id="inserUser2" parameterType="map" >
        insert into t_user(id, username, password) values(#{userId},#{userName},#{userPassWord})
    </insert>

    <select id="getAllUser" resultType="com.chen.mybatis.pojo.User">
        select * from t_user
    </select>

    <select id="getAllUser2" parameterType="String" resultType="com.chen.mybatis.pojo.User">
        select * from t_user where username like "%"#{value}"%"
    </select>

    <select id="getUserByLimit" parameterType="map" resultType="com.chen.mybatis.pojo.User">
        select * from t_user limit #{startIndex},#{pageSize}
    </select>

    <select id="getUserById" parameterType="int" resultType="com.chen.mybatis.pojo.User">
        select * from t_user where id = #{id}
    </select>

</mapper>

6.编写Mybatis工具类

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //读取MyBatis的核心配置文件
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //创建SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            //通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,生产SqlSession对象
            sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        //参数true为设置自动提交
        return sqlSessionFactory.openSession(true);
    }
}

7.测试

注:增删改语句需要提交事务

插入语句insertUser

public class MybatisTest {
    @Test
    public void testMybatis() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //通过代理模式创建UserMapper接口的代理实现类对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,通过调用的方法名匹配映射文件中的SQL标签,并执行标签中的SQL语句
        int res = userMapper.insertUser(new User(1,"王五","123",23,"男","123@.qq.com"));
        if(res > 0){
            System.out.println("插入成功");
        }
        //插入语句需要提交事务:sqlSession.commit(),这里因为我们工具类中设置了自动提交,所有可以不写;
        sqlSession.close();
    }
}

插入语句insertUser2

public class MybatisTest {
    @Test
    public void testMybatis() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //通过代理模式创建UserMapper接口的代理实现类对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId",5);
        map.put("userName","小明");
        map.put("userPassWord","123");
        userMapper.inserUser2(map);
sqlSession.close(); } }

查询所有语句getAllUser

public class MybatisTest {
    @Test
    public void testMybatis() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //通过代理模式创建UserMapper接口的代理实现类对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,通过调用的方法名匹配映射文件中的SQL标签,并执行标签中的SQL语句
        List<User> allUser = userMapper.getAllUser();
        allUser.forEach(user -> System.out.println(user));
sqlSession.close(); } }

模糊查询语句getAllUser2

public class MybatisTest {
    @Test
    public void testMybatis() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //通过代理模式创建UserMapper接口的代理实现类对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        List<User> userList = userMapper.getAllUser2("王");
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
}

分页查询语句getUserByLimit

public class MybatisTest {
    @Test
    public void testMybatis() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        HashMap map = new HashMap<String, Integer>();
        map.put("startIndex",0);
        map.put("pageSize",2);
        List<User> userList = userMapper.getUserByLimit(map);
        for(User user:userList){
            System.out.println(user);
        }
        sqlSession.close();
    }
}

根据ID查询语句getUserById

public class MybatisTest {
    @Test
    public void testMybatis() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //通过代理模式创建UserMapper接口的代理实现类对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,通过调用的方法名匹配映射文件中的SQL标签,并执行标签中的SQL语句
        User user = userMapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }
}

8.resultMap

是为了解决我们实体类属性与我们数据库字段不一致的情况,假如现在我们数据库表有id、username、password属性,然后我们创建一个实体类

实体类

public class User {

    private Integer id;
    private String username;
    private String pwd;//get、set、toString、有参无参构造也要记得配置上,这里省略掉了
}

可以看出我们User实体类中的属性是pwd和表中的password不一致

Mapper接口

public interface UserMapper {
  
    /**
     * 根据ID查询用户
     */
    User getUserById(int id);

}

Mapper.xml

此时我们就需要使用resultMap结合结果映射集才可以把我们的结果完好的输出出来了

<?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.chen.mybatis.mapper.UserMapper">

    <!--结果映射集,id对应着下方resultMap里定义的名称-->
    <resultMap id="UserMap" type="com.chen.mybatis.pojo.User">
        <!--column为数据库中的字段,propety为实体类中的属性-->
        <result column="password" property="pwd" />
    </resultMap>

    <select id="getUserById" parameterType="int" resultMap="UserMap">
        select * from t_user where id = #{id}
    </select>

</mapper>

测试类

@Test
    public void testMybatis() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
      
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
       
        User user = userMapper.getUserById(2);
        System.out.println(user);
        sqlSession.close();
    }

 

posted @ 2022-03-20 23:17  RFAA  阅读(36)  评论(0编辑  收藏  举报