三Mybatis 操作数据库

Posted archerLuo罗

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了三Mybatis 操作数据库相关的知识,希望对你有一定的参考价值。

  • 源码地址:https://github.com/RononoaZoro/mybatis-book/tree/master 的 mybatis-book ( mybatis-chapter04 )
  • 文章内容出自《Mybatis 3 源码深度解析》第四章

1、使用 Mybatis 操作数据库

1)、Mybatis 的主配置文件

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>
	<settings>
		<setting name="useGeneratedKeys" value="true"/>
		<setting name="mapUnderscoreToCamelCase" value="true"/>
		<setting name="logImpl" value="LOG4J"/>
	</settings>

	<environments default="dev" >
		<environment id="dev">
			<transactionManager type="JDBC">
				<property name="" value="" />
			</transactionManager>
			<dataSource type="UNPOOLED">
				<property name="driver" value="org.hsqldb.jdbcDriver" />
				<property name="url" value="jdbc:hsqldb:mem:mybatis" />
				<property name="username" value="sa" />
				<property name="password" value="" />
			</dataSource>
		</environment>
		<environment id="qa">
			<transactionManager type="JDBC">
				<property name="" value="" />
			</transactionManager>
			<dataSource type="UNPOOLED">
				<property name="driver" value="org.hsqldb.jdbcDriver" />
				<property name="url" value="jdbc:hsqldb:mem:mybatis_qa" />
				<property name="username" value="admin" />
				<property name="password" value="admin" />
			</dataSource>
		</environment>
	</environments>

	<mappers>
		<mapper resource="com/blog4java/mybatis/example/mapper/UserMapper.xml"/>
		<!--
		<mapper resource="file:///mybatis/com/blog4java/mybatis/example/mapper/UserMapper.xml"/>
		<mapper class="com.blog4java.mybatis.com.blog4java.mybatis.example.mapper.UserMapper"/>
		<package name="com.blog4java.mybatis.com.blog4java.mybatis.example.mapper"/>
		-->
	</mappers>
</configuration>

2)、Java 实体

package com.blog4java.mybatis.example.entity;

import lombok.Data;

import java.util.Date;

@Data
public class UserEntity {
    private Long id;
    private String name;
    private Date createTime;
    private String password;
    private String phone;
    private String nickName;
}

3)、Mapper 文件

package com.blog4java.mybatis.example.mapper;

import com.blog4java.mybatis.example.entity.UserEntity;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper {

    List<UserEntity> listAllUser();

    @Select("select * from user where id=#{userId,jdbcType=INTEGER}")
    UserEntity getUserById(@Param("userId") String userId);

    List<UserEntity> getUserByEntity( UserEntity user);

    UserEntity getUserByPhone(@Param("phone") String phone);

}
<?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.blog4java.mybatis.example.mapper.UserMapper">
    <sql id="userAllField">
      id,create_time, name, password, phone, nick_name
    </sql>

    <select id="listAllUser"  resultType="com.blog4java.mybatis.example.entity.UserEntity" >
        select
        <include refid="userAllField"/>
        from user
    </select>

    <select id="getUserByEntity"  resultType="com.blog4java.mybatis.example.entity.UserEntity">
        select
        <include refid="userAllField"/>
        from user
        <where>
            <if test="id != null">
                AND id = #{id}
            </if>
            <if test="name != null">
                AND name = #{name}
            </if>
            <if test="phone != null">
                AND phone = #{phone}
            </if>
        </where>
    </select>

    <select id="getUserByPhone" resultType="com.blog4java.mybatis.example.entity.UserEntity">
        select
        <include refid="userAllField"/>
        from user
        where phone = ${phone}
    </select>
</mapper>

4)、通过 Mybatis 提供的 API 执行

package com.blog4java.mybatis.example;

import com.alibaba.fastjson.JSON;
import com.blog4java.common.DbUtils;
import com.blog4java.mybatis.example.entity.UserEntity;
import com.blog4java.mybatis.example.mapper.UserMapper;
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.apache.ibatis.session.SqlSessionManager;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;

public class MybatisExample {

    @Before
    public void initData() {
        DbUtils.initData();
    }

    @Test
    public  void testMybatis () throws IOException {
        // 获取配置文件输入流
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        // 通过SqlSessionFactoryBuilder的build()方法创建SqlSessionFactory实例
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 调用openSession()方法创建SqlSession实例
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 获取UserMapper代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        // 执行Mapper方法,获取执行结果
        List<UserEntity> userList = userMapper.listAllUser();
         /*
        // 兼容Ibatis,通过Mapper Id执行SQL操作
        List<UserEntity> userList = sqlSession.selectList(
                "com.blog4java.mybatis.com.blog4java.mybatis.example.mapper.UserMapper.listAllUser");
        */
        System.out.println(JSON.toJSONString(userList));
    }

    @Test
    public void testSessionManager() throws IOException {
        Reader mybatisConfig = Resources.getResourceAsReader("mybatis-config.xml");
        SqlSessionManager sqlSessionManager = SqlSessionManager.newInstance(mybatisConfig);
        sqlSessionManager.startManagedSession();
        UserMapper userMapper = sqlSessionManager.getMapper(UserMapper.class);
        List<UserEntity> userList = userMapper.listAllUser();
        System.out.println(JSON.toJSONString(userList));
    }
}

以上是关于三Mybatis 操作数据库的主要内容,如果未能解决你的问题,请参考以下文章

解析Mybatis入门第三天

技术应用mybatis数据库操作(insertupdatedelete)返回值为0的场景

Spring+SpringMVC+MyBatis+Maven框架整合

#yyds干货盘点# mybatis源码解读:executor包(语句处理功能)

普通的Spring+SpringMVC+mybatis整合项目

markdown [mybatis参考]关于mybatis #mybatis的一些片段