Mybaits初识

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014714713/article/details/76543552

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

快速入门
引入mybatis核心包,mysql驱动包,log4j用于输出日志,打印sql语句

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.1</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.18</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>

log4j.properties配置

log4j.rootLogger=DEBUG,Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.org.apache=INFO

编写配置文件Configuration.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">
                <property name="" value="" />
            </transactionManager>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybaits_message" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>

    <!-- 引入映射文件 -->
    <mappers>
        <mapper resource="com/lmr/mybaits/bean/Message.xml" />
        <mapper resource="com/lmr/mybaits/bean/Command.xml" />
        <mapper resource="com/lmr/mybaits/bean/CommandContent.xml" />
    </mappers>

</configuration>

配置mapper映射文件Message.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="Message">

    <resultMap type="com.lmr.mybaits.bean.Message" id="MessageResult">
        <id column="ID" jdbcType="INTEGER" property="id" />
        <result column="COMMAND" jdbcType="VARCHAR" property="command" />
        <result column="DESCRIPTION" jdbcType="VARCHAR" property="description" />
        <result column="CONTENT" jdbcType="VARCHAR" property="content" />
    </resultMap>

    <select id="queryMessageList" parameterType="com.lmr.mybaits.bean.Message" resultMap="MessageResult">
        select <include refid="columns" /> from message
        <where>
            <if test="command != null and !&quot;&quot;.equals(command.trim())">
                and COMMAND=#{command}
            </if>
            <if test="description != null and !&quot;&quot;.equals(description.trim())">
                and DESCRIPTION like '%' #{description} '%'
            </if>
        </where>
    </select>

    <sql id="columns">ID,COMMAND,DESCRIPTION,CONTENT</sql>

</mapper>

与映射文件Message对应的bean类

/**
 * 对应的数据库中的message表
 */
public class Message {

    /**
     * 主键
     */
    private int id;
    /**
     * 指令
     */
    private String command;
    /**
     * 简要描述
     */
    private String description;
    /**
     * 回复内容
     */
    private String content;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCommand() {
        return command;
    }
    public void setCommand(String command) {
        this.command = command;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "Message [id=" + id + ", command=" + command + ", description=" + description + ", content=" + content
                + "]";
    }

}

SqlSession的作用
1. 向SQL语句传入参数
2. 执行SQL语句
3. 获取执行SQL语句的结果
4. 事务的控制

如何获取SqlSession

public SqlSession mybaitsAccess() throws IOException{

    //通过配置文件获取数据库连接信息
    Reader reader=Resources.getResourceAsReader("Configuration.xml");
    //通过配置信息构建一个SqlSessionFactory
    SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
    //通过SqlSessionFactory打开一个数据库会话
    SqlSession sqlSession=factory.openSession();

    return sqlSession;

}

获取数据
两种方式:常规方式、面向接口方式

1.常规方式:调用sqlSession中的selectList方法,该方法有两个参数,第一个参数为映射文件中配置的namespace和要执行的sql语句的id,第二个参数为要传入该条sql语句中的变量,类型与该条sql语句中的parameterType相同(即com.lmr.mybaits.bean.Message),该方法的返回值为List< Message >,list的类型则是在该条语句中的resultMap中配置(即MessageResult)

public List<Message> listMessage(Message message) {

    List<Message> messagelist = new ArrayList<>();

    DBAccess dbAccess=new DBAccess();
    SqlSession sqlSession=null;
    try {
        //获取SqlSession
        sqlSession=dbAccess.mybaitsAccess();

        //向数据库中查询数据
        messagelist=sqlSession.selectList("Message.queryMessageList", message);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if(sqlSession!=null){
            sqlSession.close();
        }
    }

    return messagelist;

}

2.面向接口方式:首先要创建一个与映射文件相对应的接口类,映射文件中的namespace要更改为接口类的详细包名(即com.lmr.mybaits.bean.ICommand),其中接口类的方法名要与映射文件中的sql语句的id相同,参数类型以及返回类型也要跟映射文件中相同。使用时,调用sqlSession中的getMapper方法,该方法的参数为接口类的class,返回值为通过动态代理生成的接口类对象,然后再使用该对象去调用对应的方法(即queryCommandList)获取结果。

//接口类
public interface ICommand {

    public List<Command> queryCommandList(Command command);

}
//映射文件
<mapper namespace="com.lmr.mybaits.bean.ICommand">

    <resultMap type="com.lmr.mybaits.bean.Command" id="CommandResult">
        <id column="C_ID" jdbcType="INTEGER" property="id"/>
        <result column="NAME" jdbcType="VARCHAR" property="name"/>
        <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
        <collection property="contentlist" resultMap="CommandContent.ContentResult" ></collection>
    </resultMap>

    <select id="queryCommandList" parameterType="com.lmr.mybaits.bean.Command" resultMap="CommandResult">
        select  a.ID C_ID,a.NAME,a.DESCRIPTION,b.ID,b.CONTENT,b.COMMANDID
        from command a left join commandcontent b on a.ID=b.COMMANDID
        <where>
            <if test="name!=null and !&quot;&quot;.equals(name.trim())">
                and a.NAME=#{name}
            </if>
        </where>
    </select>

</mapper>
public List<Command> queryCommandList(Command command){

    List<Command> commandlist=new ArrayList<>();

    DBAccess dbAccess=new DBAccess();
    SqlSession sqlSession=null;

    try{

        sqlSession=dbAccess.mybaitsAccess();

        //向数据库中查询数据
        ICommand iCommand=sqlSession.getMapper(ICommand.class);
        commandlist=iCommand.queryCommandList(command);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        if(sqlSession!=null){
            sqlSession.close();
        }
    }

    return commandlist;

}

MyBaits中的OGNL表达式
这里写图片描述

这里写图片描述

1.resultMap和resultType:
当配置resultType时,就不需要配置resultMap,看似resultType方便,但是会被受限制,没有resultMap开放多。
相同点:都是表示查询结果集的类型。
不同点:resultMap需要手动配置映射关系,而resultType是直接指定java类型或者自定义的实体类型,查询结果集的列名必须和实体属性名称一致(实体类:名称大小写可以忽略;java类型,如Map集合的key大小写要一致,尽量都大小写规范,如果不放心可以select ID id,…)。
优缺点:
1)resultType结果集列名要与java属性名一样,但是resultMap不受限制,因为resultMap有column来规定。
2)由于SQL类型与Java中类型部分不匹配,resultMap可以通过typeHandler=”“来匹配(如:SQL中的0和1来表示java中的false和true;Date类型的转换),但是resultType无能为力。

2.parameterMap和patameterType:
表示传入参数的对应关系,前者不推荐使用,只是mybatis为了适应以前的版本。前者为映射关系,后者为类型。

3.# { }和${ }:

相同点:都是用来作为占位符。
不同点:#{}在预编译的时候会被替换为?,而${}在预编译的时候直接将变量的值替换进去,而且没有引号(所以有时还要加上“'${...}'”),故一般都是用前者,个别情况会使用后者。如需进行排序,且排序字段为参数时可以使用${}(order by后面不喜欢被预编译,所以使用${}更为恰当)。

4.#{}和ognl:
在#{}中如果是基本类型,其中的名称可以随便写(不推荐),但一般都用 _parameter ,因为值唯一,而ognl中必须写成 _parameter 的方式

猜你喜欢

转载自blog.csdn.net/u014714713/article/details/76543552