mybatis 运用mapper开发

2019-02-26  本文已影响0人  林太浪先生

转自https://blog.csdn.net/xiangshuai198807/article/details/78640647

mapper接口(相当于dao接口),但不用再写mapper接口的实现类了,直接用mapper接口的代理对象来操作/ 创建mapper对象 -- DBUserMapper对象

        SqlSessionsqlsession =sqlSessionFactory.openSession();

        DBUserMappermapper = sqlsession.getMapper(DBUserMapper.class);

用mapper对象来操作sql即可

Mapper代理使用的是jdk的代理策略

Mapper代理的开发规范

1、  mapper接口的全限定名要和mapper映射文件的namespace值一致。

2、  mapper接口的方法名称要和mapper映射文件的statement的id一致。

3、  mapper接口的方法参数类型要和mapper映射文件的statement的parameterType的值一致,而且它的参数是一个。

4、  mapper接口的方法返回值类型要和mapper映射文件的statement的resultType的值一致。

说简单点,其实mapper开发和我们dao开发是一样的,但不用再创建mapper接口的实现类,就是将dao接口换成mapper接口,

其实和dao接口一样也是个接口,只是这个接口要满足如上 mapper代理开发的开发规范,然后直接DBUserMapper mapper= sqlsession.getMapper(DBUserMapper.class),再用mapper操作sql完成持久化即可。

步骤:

Jar包导入,生成数据库表,创建与src同级资源目录config,test目录(注意,config,test均为资源目录)

Mybatis开发方式之mapper代理开发—mybatis推荐的开发方式,和我写过的最简单的2dao接口开发方式,和hibernate写demo差不多一模一样,改成遵守一系列规范的mapper接口和其实现类而已,也是先创建实体类DBUser,再建实体类对应的映射文件DBUserMapper.xml(局部xml文件),再将DBUserMapper.xml mapper到SqlMapConfig.xml(全局配置文件),再严格按照DBUserMapper.xml的sql弄个mapper接口DBUserMapper(此接口的全类名对应DBUserMapper.xml 的namespane标签,方法名对应DBUserMapper.xml的sql id,方法参数和返回类型也需与DBUserMapper.xml对应),无须弄mapper接口的实现类直接 再弄个测试类Demo1来测下即可

1.创建实体类:

DBUser.java

package com.xiangshuai.mybatis.pojo;

import java.util.Date;

public classDBUser {

    private int id;

    private Integer sex;

    private Date birthday;

    private String address;

    private String username;

    public DBUser(Integer sex, Date birthday, String address, String username) {

        super();

        this.sex = sex;

        this.birthday = birthday;

        this.address = address;

        this.username = username;

    }

    public DBUser() {

        super();

        // TODO Auto-generated constructor stub

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public int getId() {

        return id;

    }

  public void setId(int id) {

        this.id = id;

    }

    public Integer getSex() {

        return sex;

    }

    public void setSex(Integer sex) {

        this.sex = sex;

    }

    public Date getBirthday() {

        return birthday;

    }

    public void setBirthday(Date birthday) {

        this.birthday = birthday;

    }

    public String getAddress() {

        return address;

    }

    public void setAddress(String address) {

        this.address = address;

    }

   @Override

    public String toString() {

        return "DBUser [id="+ id + ", sex="+ sex+ ", birthday=" + birthday+ ", address=" + address+ ", username="

                +username + "]";

    }

}

2.建实体类对应的映射文件DBUserMapper.xml(局部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">

<!-- namespace:命名空间,对statement的信息进行分类管理 -->

<!-- 注意:在mapper代理时,它具有特殊及重要的作用,在这里 namespace="com.xiangshuai.mybatis.mapper.DBUserMapper"

对应mapper接口DBUserMapper的全类名-->

<mapper namespace="com.xiangshuai.mybatis.mapper.DBUserMapper">

    <!-- 根据用户ID查询用户信息 -->

    <!-- select:表示一个MappedStatement对象 -->

    <!-- id:statement的唯一标示  === 在这里对应mapper接口DBUserMapper的方法名 -->

    <!-- #{}:表示一个占位符? -->

    <!-- #{id}:里面的id表示输入参数的参数名称,如果该参数是简单类型,那么#{}里面的参数名称可以任意 -->

    <!-- parameterType:输入参数的java类型    ===  对应mapper接口DBUserMapper的参数类型-->

    <!-- resultType:输出结果的所映射的java类型(单条结果所对应的java类型  ===

    对应mapper接口DBUserMapper的方法返回类型-) -->

    <select id="findDBUserById" parameterType="int"

        resultType="com.xiangshuai.mybatis.pojo.DBUser">

        SELECT* FROM DBUSER WHERE id =#{id}

    </select>

    <update id="udateDBUser" parameterType="com.xiangshuai.mybatis.pojo.DBUser">

           UPDATE DBUSER SET username=#{username},sex=#{sex},birthday=#{birthday},address=#{address}where id=#{id}

    </update>

    <delete id="deleteDBUser" parameterType="int">

            DELETE FROM DBUSER WHERE id=#{id}

    </delete>

    <!-- 增加后入参的dbuser对象仍然没有带id,如果要数据库持久化后入参带id,则需要在insert标签中加seleteKey标签从数据库中将id

    查出来再赋予给入参下个id="insertDBUser1"就是mysql主键是int类型自增就是这样的 -->

    <insert id="insertDBUser" parameterType="com.xiangshuai.mybatis.pojo.DBUser">

         INSERT INTO DBUSER

         (username,birthday,sex,address)

            VALUES(#{username},#{birthday},#{sex},#{address});

    </insert>

    <!-- 根据用户名称模糊查询用户列表 -->

    <!-- ${}:表示一个sql的连接符,会原样输出,而#{}会转成varchar也就是String类型

    比如一个id为int类型id=3  #{id}后会变成'3' 但${value}就是3-->

    <!-- ${value}:里面的value表示输入参数的参数名称,如果该参数是简单类型,那么${}里面的参数名称必须是value -->

    <!-- ${}这种写法存在sql注入的风险,所以要慎用!!但是在一些场景下,必须使用${},比如排序时,动态传入排序的列名,${}会原样输出,-->

    <select id="findDBUsersByName" parameterType="java.lang.String"

        resultType="com.xiangshuai.mybatis.pojo.DBUser">

        SELECT* FROM DBUSER WHERE username LIKE '%${value}%'

    </select>

    <!-- 测试用 mysql concat()完成模糊查询用户列表 -->

    <select id="findDBUsersByNameConcat" parameterType="java.lang.String"

        resultType="com.xiangshuai.mybatis.pojo.DBUser">

        SELECT* FROM DBUSER WHERE username LIKE concat('%',#{name},'%')

    </select>

    <!-- 添加用户 -->

    <!-- selectKey:查询主键,在标签内需要输入查询主键的sql -->

    <!-- order:指定查询主键的sql和insert语句的执行顺序,相当于insert语句来说

    AFTER之后也就是在执行完insert完成持久化记录之后  将这条记录的id查出来再赋值给入参参数DBUse对象 -->

    <!-- LAST_INSERT_ID:该函数是mysql的函数,获取自增主键的ID,它必须配合insert语句一起使用  -->

    <insert id="insertDBUser1" parameterType="com.xiangshuai.mybatis.pojo.DBUser">

        <selectKey keyProperty="id" resultType="int"order="AFTER">

            SELECTLAST_INSERT_ID()

        </selectKey>

        INSERTINTO DBUSER

        (username,birthday,sex,address)

        VALUES(#{username},#{birthday},#{sex},#{address})

    </insert>

    <!-- 自增主键之UUID -->

    <insert id="insertDBUser2" parameterType="com.xiangshuai.mybatis.pojo.DBUser">

        <selectKey keyProperty="id" resultType="string"order="BEFORE">

            SELECTUUID()

        </selectKey>

        INSERTINTO DBUSER

        (id,username,birthday,sex,address)

        VALUES(#{id},#{username},#{birthday},#{sex},#{address})

    </insert>

    <!-- 自增主键之UUID oralce序列自增-->

    <insert id="insertDBUser3" parameterType="com.xiangshuai.mybatis.pojo.DBUser">

        <selectKey keyProperty="id" resultType="int"order="BEFORE">

            SELECTseq.nextval FROM dual

        </selectKey>

        INSERTINTO DBUSER

        (id,username,birthday,sex,address)

        VALUES(#{id},#{username},#{birthday},#{sex},#{address})

    </insert>

</mapper>

4.严格参照DBUserMapper.xml 按照mapper规范创建mapper接口DBUserMapper.java

packagecom.xiangshuai.mybatis.mapper;

import java.util.List;

importcom.xiangshuai.mybatis.pojo.DBUser;

public interface DBUserMapper {

    public DBUser findDBUserById(Integer id);

    public void udateDBUser(DBUser user);

    public void deleteDBUser(Integer id);

    public void insertDBUser(DBUser user);

    public void  insertDBUser1(DBUseruser);

    public List<DBUser> findDBUsersByName(String username);

    public List<DBUser> findDBUsersByNameConcat(String username);

}    

5.测试类Demo1.java  

package com.xiangshuai.test;

import java.io.IOException;

import java.io.InputStream;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.List;

importorg.apache.ibatis.io.Resources;

importorg.apache.ibatis.session.SqlSession;

importorg.apache.ibatis.session.SqlSessionFactory;

importorg.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.junit.Before;

import org.junit.Test;

import com.xiangshuai.mybatis.mapper.DBUserMapper;

importcom.xiangshuai.mybatis.pojo.DBUser;

public class Demo1 {

          /*mybatis开发方式mapper开发非mapper开始: 查询,操作和hibernate很像,也是先造实体类,然后配实体类的XML映射文件,然后将实体类的XML映射文件mapper到全局映射 XML文件

           SqlMapConfig.xml中去,

           * */

         privateSqlSessionFactory sqlSessionFactory;

         @Before

         publicvoid before(){

                   //读取配置文件

                   //全局配置文件的路径

                   Stringresource = "SqlMapConfig.xml";

                   InputStreaminputStream = null;

                   try{

                            inputStream= Resources.getResourceAsStream(resource);

                   }catch (IOException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }

                   //创建SqlSessionFactory

                    sqlSessionFactory = newSqlSessionFactoryBuilder().build(inputStream);

         }

         @Test

   public void findDBUserById(){

                   //创建mapper对象 -- DBUserMapper对象

                   SqlSessionsqlsession = sqlSessionFactory.openSession();

                   DBUserMappermapper = sqlsession.getMapper(DBUserMapper.class);

                   //调用mapper完成 增删改查方法

                   DBUseruser = mapper.findDBUserById(31);

                   sqlsession.close();

                   System.out.println(user);

   }

         //模糊查询之 like'%${value}%',之所以不用 %#{username}%是因为 mybatis 将#{username}转成 %'诗'%而不是像${}原样输出

                   @Test

             public void findDBUserByUsername(){

                            //创建mapper对象 -- DBUserMapper对象

                            SqlSessionsqlsession = sqlSessionFactory.openSession();

                            DBUserMappermapper = sqlsession.getMapper(DBUserMapper.class);

                            //调用mapper完成 增删改查方法

                            //第一个参数:表示statement的唯一标示,namespace.id(DBUserMapper.xml中sql标签 id)

                 List<DBUser> users=mapper.findDBUsersByName("诗");

                 sqlsession.close();

                            System.out.println(users);

             }

                  // 测试用 mysql concat()完成 模糊查询用户列表

                   @Test

             public void findDBUsersByNameConcat(){

                            //创建mapper对象 -- DBUserMapper对象

                            SqlSessionsqlsession = sqlSessionFactory.openSession();

                            DBUserMappermapper = sqlsession.getMapper(DBUserMapper.class);

                            //调用mapper完成 增删改查方法

                            //第一个参数:表示statement的唯一标示,namespace.id(DBUserMapper.xml中sql标签 id)

                 List<DBUser> users=mapper.findDBUsersByNameConcat("诗");

                 sqlsession.close();

                            System.out.println(users);

             }

         @Test

         publicvoid updateDBUser(){

                   //创建mapper对象 -- DBUserMapper对象

                   SqlSessionsqlsession = sqlSessionFactory.openSession();

                   DBUserMappermapper = sqlsession.getMapper(DBUserMapper.class);

                   //调用mapper完成 增删改查方法

                DBUser user = mapper.findDBUserById(31);

                user.setSex(2);user.setUsername("刘小敏");

                mapper.udateDBUser(user);

                sqlsession.commit();

                sqlsession.close();

         }

         @Test

         publicvoid deleteDBUserById(){

                   //创建mapper对象 -- DBUserMapper对象

                   SqlSessionsqlsession = sqlSessionFactory.openSession();

                   DBUserMappermapper = sqlsession.getMapper(DBUserMapper.class);

                   //调用mapper完成 增删改查方法;

                mapper.deleteDBUser(38);

                sqlsession.commit();

                sqlsession.close();

         }

         //在insert标签中不加selectKey标签,不返回id给dbuser对象的增加测试

         @Test

         publicvoid insertUser() throws ParseException{

                   //创建mapper对象 -- DBUserMapper对象

                   SqlSessionsqlsession = sqlSessionFactory.openSession();

                   DBUserMappermapper = sqlsession.getMapper(DBUserMapper.class);

                   //调用mapper完成 增删改查方法

                   SimpleDateFormatsdf = new SimpleDateFormat("yyyy-MM-dd");

                   Dateda = sdf.parse("1997-11-12");

                   DBUseruser = new DBUser(1,da,"广西梧州","刘小诗");

                   mapper.insertDBUser(user);

                   sqlsession.commit();

             sqlsession.close();

                   System.out.println(user);//打印结果无id,但数据库中已经有这条id记录  DBUser [id=0, sex=1, birthday=Wed Nov 1200:00:00 CST 1997, address=广西梧州, username=刘小诗]

         }

         //在insert标签中加selectKey标签,并且 设order="AFTER"表示在insert持久化后将这条记录的id查出粜,赋给入参 dbuser对象的增加测试

         @Test

         publicvoid insertUserHaveId() throws ParseException{

                   //创建mapper对象 -- DBUserMapper对象

                   SqlSessionsqlsession = sqlSessionFactory.openSession();

                   DBUserMappermapper = sqlsession.getMapper(DBUserMapper.class);

                   //调用mapper完成 增删改查方法

                   SimpleDateFormatsdf = new SimpleDateFormat("yyyy-MM-dd");

                   Dateda = sdf.parse("1997-11-13");

                   DBUseruser = new DBUser(1,da,"北京西城","刘诗诗");

                   mapper.insertDBUser1(user);

                   sqlsession.commit();

             sqlsession.close();

                   System.out.println(user);//打印结果带id的DBUser[id=36, sex=1, birthday=Thu Nov 13 00:00:00 CST 1997, address=北京西城,username=刘诗诗]

         }

}

上一篇下一篇

猜你喜欢

热点阅读