mybatis

Posted carl_ysz

tags:

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

一、MyBatis简介

MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plan Old Java Objects,普通的 Java 对象)映射成数据库中的记录。

orm工具的基本思想

无论是用过的 hibernate,Mybatis,你都可以法相他们有一个共同点:

  1. 从配置文件(通常是 XML 配置文件中)得到 sessionfactory.
  2. 由 sessionfactory 产生 session
  3. 在 session 中完成对数据的增删改查和事务提交等.
  4. 在用完之后关闭 session 。
  5. 在 Java 对象和 数据库之间有做 mapping 的配置文件,也通常是 xml 文件。

二、HelloWorld

创建用户表:

Create TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(50) DEFAULT NULL,
  `userAge` int(11) DEFAULT NULL,
  `userAddress` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Insert INTO `user` VALUES (\'1\', \'summer\', \'100\', \'shanghai,pudong\');

结构图如下:

Configuration.xml: 这里使用mariadb作为开发环境

<?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>
    <typeAliases>
        <typeAlias alias="User" type="demo.mybatis.helloworld.model.User"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="org.mariadb.jdbc.Driver"/>
                <property name="url" value="jdbc:mariadb://192.168.1.202:3306/demo" />
                <property name="username" value="root"/>
                <property name="password" value="111111"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/User.xml"/>
    </mappers>
</configuration>

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>demo</groupId>
    <artifactId>mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>1.4.6</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

User.xml:

<?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="demo.mybatis.helloworld.mapper.UserMapper">
    <select id="selectUserByID" parameterType="int" resultType="User">
        select * from `user` where id = #{id}
    </select>
</mapper>

User.java:

public class User {
    private int id;
    private String userName;
    private Integer userAge;
    private String userAddress;
    //get and set...
}

UserMapper:

public interface UserMapper {
    User selectUserByID(int id);
}

Test.java:

import java.io.Reader;

import demo.mybatis.helloworld.mapper.UserMapper;
import demo.mybatis.helloworld.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Created by carl.yu on 2016/12/8.
 */
public class Test {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSession() {
        return sqlSessionFactory;
    }

    public static void main(String[] args) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            UserMapper userOperation=session.getMapper(UserMapper.class);
            User user = userOperation.selectUserByID(1);
            System.out.println(user.getUserAddress());
            System.out.println(user.getUserName());
        } finally {
            session.close();
        }
    }
}

三、CRUD

这里直接用接口的方式编程。这种方式,要注意的一个地方就是。在 User.xml 的配置文件中,mapper namespace="demo.mybatis.helloworld.mapper.UserMapper" ,命名空间非常重要,不能有错,必须与我们定义的 package 和 接口一致。如果不一致就会出错,这一章主要在上一讲基于接口编程的基础上完成如下事情:

  1. 用 mybatis 查询数据,包括列表
  2. 用 mybatis 增加数据
  3. 用 mybatis 更新数据
  4. 用 mybatis 删除数据

1. 查询数据,前面已经讲过简单的,主要看查询出列表的

查询出列表,也就是返回 list, 在我们这个例子中也就是 List , 这种方式返回数据,需要在 User.xml 里面配置返回的类型 resultMap, 注意不是 resultType, 而这个 resultMap 所对应的应该是我们自己配置的

<!-- 为了返回list 类型而定义的returnMap -->
    <resultMap type="User" id="resultListUser">
        <id column="id" property="id" />
        <result column="userName" property="userName" />
        <result column="userAge" property="userAge" />
        <result column="userAddress" property="userAddress" />
    </resultMap>

查询列表的语句在 User.xml 中

<!-- 返回list 的select 语句,注意 resultMap 的值是指向前面定义好的 -->
    <select id="selectUsers" parameterType="string" resultMap="resultListUser">
        select * from user where userName like #{userName}
    </select>

在 UserMapper接口中增加方法:public List selectUsers(String userName);

现在在 Test 类中做测试

public void getUserList(String userName){
        SqlSession session = sqlSessionFactory.openSession();
        try {
            UserMapper userOperation=session.getMapper(UserMapper.class);           
            List<User> users = userOperation.selectUsers(userName);
            for(User user:users){
                System.out.println(user.getId()+":"+user.getUserName()+":"+user.getUserAddress());
            }

        } finally {
            session.close();
        }
    }

现在在 main 方法中可以测试:

public static void main(String[] args) {
        Test testUser=new Test();
        testUser.getUserList("%");
    }

 

可以看到,结果成功查询出来。如果是查询单个数据的话,用第二讲用过的方法就可以了。

2. 用 mybatis 增加数据

在 UseMapper接口中增加方法:

public void addUser(User user);

在 User.xml 中配置

<!--执行增加操作的SQL语句。id和parameterType  
       分别与UserMapper接口中的addUser方法的名字和  
       参数类型一致。以#{name}的形式引用Student参数  
       的name属性,MyBatis将使用反射读取Student参数  
       的此属性。#{name}中name大小写敏感。引用其他  
       的gender等属性与此一致。seGeneratedKeys设置  
       为"true"表明要MyBatis获取由数据库自动生成的主  
       键;keyProperty="id"指定把获取到的主键值注入  
       到Student的id属性--> 
    <insert id="addUser" parameterType="User" 
        useGeneratedKeys="true" keyProperty="id"> 
        insert into user(userName,userAge,userAddress)  
             values(#{userName},#{userAge},#{userAddress})  
    </insert>

然后在 Test 中写测试方法:

/**
     * 测试增加,增加后,必须提交事务,否则不会写入到数据库.
     */
    public void addUser(){
        User user=new User();
        user.setUserAddress("人民广场");
        user.setUserName("飞鸟");
        user.setUserAge(80);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            UserMapper userOperation=session.getMapper(UserMapper.class);
            userOperation.addUser(user);
            session.commit();
            System.out.println("当前增加的用户 id为:"+user.getId());
        } finally {
            session.close();
        }
    }

3. 用 mybatis 更新数据

方法类似,先在 UserMapper中增加方法:

public void updateUser(User user);

然后配置 User.xml

<update id="updateUser" parameterType="User" >
        update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
   </update>

Test 类总的测试方法如下:

public void updateUser(){
        //先得到用户,然后修改,提交。
        SqlSession session = sqlSessionFactory.openSession();
        try {
            UserMapper userOperation=session.getMapper(UserMapper.class);
            User user = userOperation.selectUserByID(4);            
            user.setUserAddress("原来是魔都的浦东创新园区");
            userOperation.updateUser(user);
            session.commit();

        } finally {
            session.close();
        }
    }

4. 用 mybatis 删除数据

同理,UserMapper增加方法:public void deleteUser(int id);

配置 User.xml

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

然后在 Test 类中写测试方法:

 /**
     * 删除数据,删除一定要 commit.
     * @param id
     */
    public void deleteUser(int id){
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation=session.getMapper(IUserOperation.class);           
            userOperation.deleteUser(id);
            session.commit();            
        } finally {
            session.close();
        }
    }

这样,所有增删改查都完成了,注意在增加,更改,删除的时候要调用 session.commit(),这样才会真正对数据库进行操作,否则是没有提交的。

到此为止,简单的单表操作,应该都会了,接下来的时间了,我会讲多表联合查询,以及结果集的选取。

四、spring boot 配置mybatis

参考文章:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

MyBatis-Spring-Boot-Starter will:

  • 自动探测 DataSource.
  • 自动根据探测到的DataSource创建SqlSessionFactoryBean .
  • Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactoryBean.
  • Autoscan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans.

可以配置的信息有:

PropertyDescription
config-location MyBatis xml config file (optional)
mapper-locations Mapper xml config files (optional)
type-aliases-package Package to search for type aliases (optional)
type-handlers-package Package to search for type aliases (optional)
executor-type Executor type: SIMPLE, REUSE, BATCH (optional)

文件图:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>demo</groupId>
    <artifactId>demo.mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>mybatis spring boot demo</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>1.4.6</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.properties:

jdbc.driverClassName=org.mariadb.jdbc.Driver
jdbc.url=jdbc:mariadb://192.168.1.202:3306/demo
jdbc.username=root
jdbc.password=111111

mybatis.config-location=classpath:mybatis-config.xml

logging.level.root=WARN
logging.level.sample.mybatis.mapper=TRACE

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>
    <typeAliases>
        <!--<package name="sample.mybatis.domain"/>-->
        <typeAlias alias="User" type="demo.domain.User"/>
    </typeAliases>
    <mappers>
        <mapper resource="mapper/User.xml"/>
    </mappers>
</configuration>

MyBatisConfig: 配置数据源

package demo;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * Created by carl.yu on 2016/12/8.
 */
@Configuration
public class MyBatisConfig {
    @Autowired
    private Environment env;

    /**
     * 创建数据源
     *
     * @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错
     */
    @Bean
    //@Primary
    public DataSource getDataSource() throws Exception {
        Properties props = new Properties();
        props.put("driverClassName", env.getProperty("jdbc.driverClassName"));
        props.put("url", env.getProperty("jdbc.url"));
        props.put("username", env.getProperty("jdbc.username"));
        props.put("password", env.getProperty("jdbc.password"));
        props.put("testWhileIdle", "false");
        return DruidDataSourceFactory.createDataSource(props);
    }
}

配置User.xml:

<?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="demo.dao.UserMapper">
    <select id="selectUserByID" parameterType="int" resultType="User">
        select * from `user` where id = #{id}
    </select>

    <resultMap type="User" id="resultListUser">
        <id SSM-MyBatis-05:Mybatis中别名,sql片段和模糊查询加getMapper

mybatis动态sql片段与分页,排序,传参的使用

MyBatis动态SQL标签用法

MYBATIS05_ifwherechoosewhentrimsetforEach标签sql片段

mybatis动态sql之利用sql标签抽取可重用的sql片段

[mybatis]动态sql_sql_抽取可重用的sql片段