MyBatis(一)单表操作

2017-03-27  本文已影响266人  忧郁的小码仔

关于MyBatis这里不再介绍,直接开始动手。
编辑器:InteIIiJ IDEA, 数据库:mysql

1.新建一个maven项目

屏幕快照 2017-03-27 下午3.26.30.png 屏幕快照 2017-03-27 下午3.26.45.png 屏幕快照 2017-03-27 下午3.26.57.png

pom.xml中添加mysql和mybatis依赖

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
    </dependencies>

2. 在mysql中新建一个testdb数据库,和一张person表

create database testdb;
use testdb;
create table person (
id  int auto_increment primary key not null,
name varchar(20) not null,
age int not null,
sex varchar(10) not null
) default charset=utf8;

注意定义表的最后指定utf8编码,同时后面指定数据源的时候也会指定utf-8编码,这样才能支持中文。

3.最后的目录结构

屏幕快照 2017-03-27 下午5.02.44.png

4.下面介绍一下每个文件的作用和用途

首先,定义一个实体类Person,注意要和数据库中的字段一一对应。

public class Person {

    private int id;
    private String name;
    private int age;
    private SEX sex;

// 构造方法和set,get方法请自行添加
}

public enum  SEX {
    MAN, WOMAN
}

然后,定义所有sql操作的mapper映射文件(PersonMapper.xml)如下:
resultType指定sql语句的返回值类型,parameterType用来指定参数类型
mapper的namespace这里暂时随便写,后面会介绍它的作用。
sql 语句语句中的参数用#{}来修饰

<?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="suibianxiede">
    <select id="selectPerson"
            resultType="Person" parameterType="Person">
        SELECT *
        FROM Person
        WHERE id = #{id}
    </select>
    <select id="selectPersonByName"
            resultType="Person">
        SELECT *
        FROM Person
        WHERE name = #{name}
    </select>
    <!--在插入的时候指定useGeneratedKeys="true",让数据库自动生成主键。-->
    <insert id="insertPerson"
            useGeneratedKeys="true">
        INSERT INTO Person (name, age, sex) VALUES (#{name}, #{age}, #{sex})
    </insert>
    <update id="updatePerson">
        UPDATE Person
        SET age = #{age}
        WHERE id = #{id}
    </update>
    <delete id="deletePerson">
        DELETE FROM Person
        WHERE id = #{id}
    </delete>
</mapper>

定义mybatis的配置文件(mybatis-config.xml),用来指定数据源,引入mapper映射文件,系统配置等等

<?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>
    <!--指定属性, 在environment中引用-->
    <properties>
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
        <property name="driver.useSSL" value="false"/>
    </properties>

    <!--系统设置-->
    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>

    <!--指定别名,这样在mapper映射文件中就可以直接使用Person,而不用使用com.archer.mybatis.Person这种全路径名-->
    <typeAliases>
        <typeAlias type="com.archer.mybatis.Person" alias="Person"/>
    </typeAliases>

    <!--配置环境,可以配置多个环境用于测试、调试和生产-->
    <!--这里environments的default字段一定要和下面的所有的environment中的一个的id字段一致,表示选用哪种数据库环境,不然在获取sqlsession的时候会报空指针错误-->
    <!--### Error opening session.  Cause: java.lang.NullPointerException-->
    <!--### Cause: java.lang.NullPointerException-->
    <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>



    <!--配置mapper映射文件-->
    <mappers>
        <mapper resource="PersonMapper.xml"/>
    </mappers>

</configuration>

创建SqlSessionFactory(Utils):

package com.archer.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by git on 2017/3/27.
 */
public abstract class Utils {

    private static volatile SqlSessionFactory sqlSessionFactory;
    public static final String configLocation = "mybatis-config.xml";

    public static SqlSessionFactory getSqlSessionFactory() throws IOException {
        if (sqlSessionFactory == null) {
            synchronized (Utils.class) {
                if (sqlSessionFactory == null) {
                    InputStream inputStream = Resources.getResourceAsStream(configLocation);
                    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                    inputStream.close();
                }
            }
        }
        return sqlSessionFactory;
    }
}

结下来,开始操作mybatis:
在创建SQLSessionFactory之后,我们需要获取MyBatis最核心的对象SqlSession,所有操作都需要SqlSession来进行。另外它是非线程安全的对象,不能放在类的静态字段上,最好也不要作为实例字段。我们要在需要的时候创建它,不用的时候及时释放。

public class Main {

    private static SqlSessionFactory sqlSessionFactory;
    public static void main(String[] args) {
        SqlSession sqlSession;
        try {
            sqlSessionFactory = Utils.getSqlSessionFactory();
            sqlSession = sqlSessionFactory.openSession(true);
//插入数据
            Person p = new Person(-1, "老刘", 152, SEX.MAN);
            sqlSession.insert("insertPerson",p);

//检索数据
            Person s = sqlSession.selectOne("selectPersonByName", p.getName());
            System.out.println(s);

//更新数据
            s.setAge(260);
            sqlSession.update("updatePerson", s);
            Person s2 = sqlSession.selectOne("selectPersonByName", p.getName());
            System.out.println(s2);

//删除数据
            sqlSession.delete("deletePerson", s.getId());
//最后,不使用的时候记得把sqlSession释放掉
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5.创建映射类

在上面的例子中,我们操作sql语句都是通过id对应的字符串来完成,这中方式比较笨拙,Mybatis提供了一种更加方便的方法来操作sql,那就是映射类。

定义一个接口类,接口中的方法名字必须和映射文件中的语句id一致,包括参数。

public interface PersonMapper {
    Person selectPerson(int id);
    Person selectPersonByName(String name);

    void insertPerson(Person person);
    void updatePerson(Person person);
    void deletePerson(Person person);
}

接下来,我们好要修改映射文件的mapper的namespace(前面提到过,一开始是随便写的),将命名空间修改为映射类的类名就能让Mybatis找到这个映射文件了。

<mapper namespace="com.archer.mybatis.PersonMapper">

配置好映射类和映射文件之后,就可以使用了,只需要通过sqlSession获取到映射类即可:

PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
Person p = new Person(-1, "老刘", 152, SEX.MAN);
mapper.insertPerson(p);

最终demo.

上一篇 下一篇

猜你喜欢

热点阅读