MyBatis入门

一、简介

1、什么是MyBatis

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。

2、官网地址

https://mybatis.org/mybatis-3/zh/index.html

3、依赖

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>

二、项目初体验

1、创建一个maven项目

2、添加依赖

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
    </dependencies>

3、创建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>
    <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/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/kw/mvc/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

4、创建mybatisUtils工具类

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory=null;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

5、创建mapper接口,mapper.xml配置文件

6、单元测试

    @Test
    public void test(){
        SqlSession sqlSession =MybatisUtils.getSqlSession();
        /*List<User> list=sqlSession.selectList("com.kw.mvc.mapper.UserMapper.getUserList");*/
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        List<User> list=userMapper.getUserList();
        for (User user : list) {
            System.out.println(user);
        } 
        sqlSession.close();
    }

注意:maven项目构建时无法获取java或者resources文件夹下的xml等配置文件,需要在pom.xml文件添加构建

    <build>
        <resources>
            <resource>
                 <directory>src/main/java</directory>
                 <includes>
                     <include>**/*.xml</include>
                     <include>**/*.properties</include>
                 </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

三、增删改查初体验

1、新增

UserMapper

void addUser(User user);

UserMapper.xml

 <insert id="addUser" parameterType="com.kw.mvc.model.User">
        insert into User(username,password) values(#{username},#{password})
 </insert>

UserMapperTest

    @Test
    public void addUser(){
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User user=new User();
        user.setUsername("王五");
        user.setPassword("123");
        userMapper.addUser(user);
        sqlSession.commit();
        sqlSession.close();
    }

2、删除

UserMapper

void deleteUserById(int id);

UserMapper.xml

    <delete id="deleteUserById" parameterType="int">
        delete from User where id=#{id}
    </delete>

UserMapperTest

   @Test
    public void deleteUserById(){
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        userMapper.deleteUserById(1);
        sqlSession.commit();
        sqlSession.close();
    }

3、修改

UserMapper

   void updateUserById(User user);

UserMapper.xml

    <update id="updateUserById" parameterType="com.kw.mvc.model.User">
        update User set username=#{username},password=#{password} where id=#{id}
    </update>

UserMapperTest

    @Test
    public void updateUserById(){
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        userMapper.updateUserById(new User(2,"李四2","456"));
        sqlSession.commit();
        sqlSession.close();
    }

4、查询所有

UserMapper

List<User> getUserList();

UserMapper.xml

<select id="getUserList" resultType="com.kw.mvc.model.User">
      select * from User
</select>

UserMapperTest

    @Test
    public void test(){
        SqlSession sqlSession =MybatisUtils.getSqlSession();
        /*List<User> list=sqlSession.selectList("com.kw.mvc.mapper.UserMapper.getUserList");*/
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        List<User> list=userMapper.getUserList();
        for (User user : list) {
            System.out.println(user);
        }
        sqlSession.close();
    }

5、根据id查询

UserMapper

 User getUserById(int id);

UserMapper.xml

    <select id="getUserById" parameterType="int" resultType="com.kw.mvc.model.User">
        select * from User where id=#{id}
    </select>

UserMapperTest

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

6、条件查询

7、开发方式

  • 原始dao开发方式
    需要创建接口实现类,实现接口中对应的方法,例如:
  • mapper动态代理方式(常用)
    1、创建mapper接口
    2、创建mapper接口对应的mapper.xml配置文件
    3、mapper配置文件需要与接口绑定:将配置文件中namespace的值设置为接口的全类名
    4、mapper配置文件中的方法需要与接口的方法名绑定:将配置文件中方法id设置为与接口中方法名一致。
    5、需要在mybatis-config-xml配置文件中注册mapper.xml文件,例如
    <mappers>
        <mapper resource="com/kw/mvc/mapper/UserMapper.xml"/>
    </mappers>

6、通过创建mapper代理对象调用方法。

UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
User user=userMapper.getUserById(2);

8、Map和模糊查询

Map:
如果查询参数比较多,可以使用Map作为参数,使用Map可以随意设置入参名称,比较灵活。

 Map<String,Object> map=new HashMap<String,Object>();
 map.put("name","张");
 map.put("pwd","123");
 List<User> list=userMapper.getUserMap(map);

模糊查询:
使用like进行模糊查询

    <select id="getUserMap" parameterType="map" resultType="com.kw.mvc.model.User">
        select * from User where username like #{name} and password=#{pwd}
        select * from User where username like "%"#{name}"%" and password=#{pwd}
        select * from User where username like '%${name}%' and password=#{pwd}
    </select>

三、mybatis-config.xml详细配置介绍

properties(属性)

可以通过properties属性引入外部的配置信息

  1. 新增db.propertis配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=123
  1. 引入外部配置文件db.properties
    在properties属性中也可以配置属性,但外部配置文件的优先级更高。
    <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="123"/>
    </properties>

settings(设置)

	<!-- 由于全局配置中:jdbcTypeForNull=OTHER,oracle不支持,以下两种方式:
		1、#{address,jdbcType=NULL};
		2、jdbcTypeForNull=NULL
	 -->
	<settings>
		<!-- 开启驼峰命名 -->
		<setting name="mapUnderscoreToCamelCase" value="true"/>
		<setting name="jdbcTypeForNull" value="NULL"/>
	</settings>

typeAliases(类型别名)

        <!-- 设置别名 -->
	<typeAliases>
		<!-- <typeAlias type="com.kw.mybaits.po.User" alias="user"/> -->
		<!-- 批量使用别名 -->
		<package name="com.kw.mybatis.po"/>
		<!-- 在批量起别名的情况下,可以使用@Alias注解为某个类型指定新的别名 -->
	</typeAliases>

typeHandlers(类型处理器)

objectFactory(对象工厂)

plugins(插件)

environments(环境配置)

	<!-- 和spring整合后将取消 -->
 	<environments default="dev_mysql">
 		<environment id="dev_mysql">
 			<transactionManager type="JDBC"/>
 			<dataSource type="POOLED">
 				<property name="driver" value="${jdbc.driver}"/>
 				<property name="url" value="${jdbc.url}"/>
 				<property name="username" value="${jdbc.username}"/>
		    	<property name="password" value="${jdbc.password}"/>
			 </dataSource>
 		</environment>
 		
 		<environment id="dev_oracle">
 			<transactionManager type="JDBC"/>
 			<dataSource type="POOLED">
 				<property name="driver" value="${orcl.driver}"/>
 				<property name="url" value="${orcl.url}"/>
 				<property name="username" value="${orcl.username}"/>
		    	<property name="password" value="${orcl.password}"/>
			</dataSource>
 		</environment>
 	</environments>

environment(环境变量)

transactionManager(事务管理器)

dataSource(数据源)

databaseIdProvider(数据库厂商标识)

<!-- 5、databaseIdProvider:支持多数据库厂商的;
		   type="DB_VENDOR":VendorDatabaseIdProvider
		         作用就是得到数据库厂商的标识(驱动getDatabaseProductName()),mybatis就能根据数据库厂商标识来执行不同的sql;
		   MySQL,Oracle,SQL Server,xxxx
	 -->
	<databaseIdProvider type="DB_VENDOR">
		<!-- 为不同的数据库厂商起别名 -->
		<property name="MySQL" value="mysql"/>
		<property name="Oracle" value="oracle"/>
		<property name="SQL Server" value="sqlserver"/>
	</databaseIdProvider>

mappers(映射器)

<mappers>
 	<mapper resource="com/kw/mybatis/helloworld/User.xml"></mapper>
 	<!-- 注册配置文件方式 -->
 	<mapper resource="mapper/UserMapper.xml"></mapper>
 	<!-- 注册接口方式:
 		 1、有sql映射文件,映射文件名必须和接口同名,并且放在与接口同一目录下。
 		        此方法需要接口和xml配置文件进行绑定
 		 2、没有sql映射文件,所有的sql都是利用注解写在接口上(不常用) -->
 	<!-- <mapper class="com.kw.mybatis.dao.UserMapper"/> -->
 	<!-- 批量扫描mapper -->
 	<!-- <package name="com.kw.mybatis.dao"/> -->
</mappers>

四、mapper.xml映射文件详细配置介绍

五、动态SQL

六、缓存

七、逆向工程

八、与spring整合

posted @ 2021-11-25 20:04  amo丶k  阅读(26)  评论(0编辑  收藏  举报