MyBatis续

2020-03-12  本文已影响0人  拼搏男孩

一、vo、po、dto、bo、pojo、entity、model的对比

二、MyBatis中#{}与${}的区别

三、Lombok的使用

1、添加依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
    <scope>provided</scope>
</dependency>

2、安装插件

IDEA与Eclipse都需要安装Lombok的插件,在各自的插件库搜索Lombok进行安装即可,比较方便

3、使用

Lombok的主要作用是帮助开发者自动生成POJO类的getter、setter、toString、equals、hashCode与构造器,在对应的类、方法上添加注解即可:

四、DTO在MyBatis中的使用

昨天使用了八个mapper文件将八张表连接在一起进行查询,实际上可以在一个xml文件中查询一次就可以了:

UserDTO.java

package com.qianfeng.pojo;

import lombok.Data;

@Data
public class UserDTO {
    private String userName;
    private double totalPrice;
    private String address;
    private String payType;
    private int num;
    private String productName;
    private String productType;
    private String image;
}

UserDTOMapper.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="com.qianfeng.pojo.UserDTO">
    <select id="getUserDTOByUid" resultType="UserDTO">
        select u.name as userName,o.price as totalPrice,addr.name as address,pty.name as payType,
        oi.num as num,p.name as productName,pt.name as productType,img.image as image
        from users u left join orders o on o.user_id=u.id left join addresses addr on addr.id=o.address
         left join pay_type pty on pty.id=o.pay_type left join order_item oi on oi.order_id=o.order_id
          left join products p on p.id=oi.product_id left join product_types pt on pt.id=p.type
          left join images img on img.product_id=p.id where u.id=#{uid}
    </select>
</mapper>

为了达到一次性查询八张表的目的,我们需要新创建一个pojo:UserDTO,它的属性包含我们需要从数据库中查找的所有的字段,然后我又创建了一个UserDTOMapper.xml的文件。这种方式和之前的八个xml文件相比,查询八表连接的字段是方便了许多,但是这种SQL语句是写死的,可重用性低,可扩展性低。

五、xml文件+接口

IUserDao.java

package com.qianfeng.dao;

import com.qianfeng.pojo.User;

import java.util.List;

public interface IUserDao {
    List<User> getAllUsers();

    User getUserById(int id);

    int saveUser(User u);

    int deleteUserById(int id);

    int updateUser(User u);
}

UserMapper2.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="com.qianfeng.dao.IUserDao">
    <select id="getAllUsers" resultType="User">
        select * from users
    </select>
    <select id="getUserById" resultType="User">
        select * from users where id = #{id}
    </select>
    <insert id="saveUser">
        insert into users values (default ,#{name},#{password},#{age})
    </insert>
    <delete id="deleteUserById">
        delete from users where id=#{id}
    </delete>
    <update id="updateUser">
        update users set name=#{name},password=#{password},age=#{age} where id=#{id}
    </update>
</mapper>

UserTest.java

package com.qianfeng.pojo;

import com.qianfeng.dao.IUserDao;
import com.qianfeng.utils.SessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;


public class UserTest {

    private SqlSession ss = null;

    @Before
    public void setUp() throws Exception {
        ss = SessionUtils.getSqlSession();
    }
    @Test
    public void testGetAllUsers(){
        IUserDao mapper = ss.getMapper(IUserDao.class);
        List<User> users = mapper.getAllUsers();
        for (User user : users) {
            System.out.println(user);
        }
    }
    @Test
    public void testGetUserById(){
        IUserDao mapper = ss.getMapper(IUserDao.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
    }
    @Test
    public void testSaveUser(){
        IUserDao mapper = ss.getMapper(IUserDao.class);
        User u = new User();
        u.setName("郭靖");
        u.setPassword("woaihuangrong");
        u.setAge(26);
        int result = mapper.saveUser(u);
        System.out.println(result);
    }
    @After
    public void tearDown() throws Exception {
        SessionUtils.closeSqlSession(ss);
    }
}

SessionUtils.java

package com.qianfeng.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class SessionUtils {
    private static SqlSessionFactory mFactory = null;
    static {
        try {
            mFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

    public static void closeSqlSession(SqlSession sqlSession){
        if(sqlSession!=null){
            sqlSession.close();
            sqlSession = null;
        }
    }
}

SessionUtils是一个工具类,专门用来创建SqlSession对象与关闭SqlSession对象。

mapper.xml文件中的namespace必须是接口的全路径,id必须是接口的方法名,接口中的方法不能重载,因为namespace+id必须唯一;接口中的增删改方法的返回值最好使用int或boolean。

在接口中我们使用IUserDao mapper = ss.getMapper(IUserDao.class);这条语句获得了一个IUserDao对象,然后调用它的方法。

六、纯注解

IUserDao2.java

package com.qianfeng.dao;

import com.qianfeng.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface IUserDao2 {
    @Select("select * from users")
    List<User> getAllUsers();
    @Select("select * from users where id = #{id}")
    User getUserById(int id);
    @Insert("insert into users values (default ,#{name},#{password},#{age})")
    int saveUser(User u);
    @Delete("delete from users where id=#{id}")
    int deleteUserById(int id);
    @Update("update users set name=#{name},password=#{password},age=#{age} where id=#{id}")
    int updateUser(User u);
    //@Select("select * from users where name = #{arg0} and password = #{arg1}")
    @Select("select * from users where name = #{param1} and password = #{param2}")
    User getUserByNameAndPassword(String name,String password);
    @Select("select * from users where name = #{name} and password = #{password}")
    User getUserByNameAndPassword2(@Param("name") String name,@Param("password") String password);
}

这种范式不需要使用Mapper.xml文件,将SQL语句以注解的形式写在对应的方法上。特别注意的是如果需要传零散值,不能传map,需要在SQL语句中使用arg0、arg1......或param1、param2或在方法中对应的形参前面加上注解@Param(),括号中的值是SQL语句中占位符。

mybatis.xml

<mappers>
<!--        <mapper class="com.qianfeng.dao.IUserDao2"/>-->
        <package name="com.qianfeng.dao"/>
    </mappers>

既然不需要使用mapper.xml文件进行注册,那么可以用另外两种方式注册,第一种方式是指定接口所在的类的路径,另外一种方式将特定包下的所有类都注册为mapper。

UserTest2.java

package com.qianfeng.pojo;

import com.qianfeng.dao.IUserDao2;
import com.qianfeng.utils.SessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;


public class UserTest2 {

    private SqlSession ss = null;

    @Before
    public void setUp() throws Exception {
        ss = SessionUtils.getSqlSession();
    }
    @Test
    public void testGetAllUsers(){
        IUserDao2 mapper = ss.getMapper(IUserDao2.class);
        List<User> users = mapper.getAllUsers();
        for (User user : users) {
            System.out.println(user);
        }
    }
    @Test
    public void testGetUserById(){
        IUserDao2 mapper = ss.getMapper(IUserDao2.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
    }
    @Test
    public void testSaveUser(){
        IUserDao2 mapper = ss.getMapper(IUserDao2.class);
        User u = new User();
        u.setName("郭靖");
        u.setPassword("woaihuangrong");
        u.setAge(26);
        int result = mapper.saveUser(u);
        System.out.println(result);
    }
    @Test
    public void testDeleteUserById(){
        IUserDao2 mapper = ss.getMapper(IUserDao2.class);
        int i = mapper.deleteUserById(4);
        System.out.println(i);
    }
    @Test
    public void testGetUserByNameAndPassword(){
        IUserDao2 mapper = ss.getMapper(IUserDao2.class);
        User u = mapper.getUserByNameAndPassword2("张三","bxxsdhiejde");
        System.out.println(u);
    }
    @After
    public void tearDown() throws Exception {
        SessionUtils.closeSqlSession(ss);
    }
}

测试类的使用方式与商议中方式一样。

上一篇下一篇

猜你喜欢

热点阅读