Writing MyBatis Dao Layer

Traditional dao layer writing

Previously, you wrote the Dao layer, creating a new package, com.chy.dao, and then writing the interface, StudentDao:

public interface StudentDao {
    public void insertStudent(Student student);

    public void updateStudent(Student student, Integer id);

    public Student selectStudent(Integer id);
}

 

Next, write the implementation class StudentDaoImpl:

public class StudentDaoImpl implements StudentDao {
    @Override
    public void insertStudent(Student student) {

    }

    @Override
    public void updateStudent(Student student, Integer id) {

    }

    @Override
    public Student selectStudent(Integer id) {
        return null;
    }
}

 

 

 

 

 

dao Layer Writing for MyBatis

MyBatis does not write dao like this.MyBatis's dao consists of two parts: the mapping file and the corresponding interface of the mapping file.

 

Create a new package, com.chy.mapper, and create a new interface under the package, StudentMapper:

public interface StudentMapper {
    public void insertStudent(Student student);

    public Student selectStudent(Integer id);
}

 

Create a new mapping file for this interface under the package, StudentMapper.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.chy.mapper.StudentMapper">
    <insert id="insertStudent" parameterType="com.chy.pojo.Student">
        INSERT INTO student_tb(name,age,score)VALUES (#{name},#{age},#{score})
    </insert>

    <select id="queryById" parameterType="Integer" resultType="Student">
        SELECT * FROM student_tb WHERE id=#{id}
    </select>
</mapper>

 

  • The file name and namespace of the mapping file should be the same as the interface name, and is Interface-oriented programming.
  • id to be the same as the method name in the interface
  • Parameter type, return value type should be the same as in the interface
  • A method in an interface can have at most one parameter, because a map file can have at most one parameter type

 

 

The mapper package is equivalent to the traditional dao package, and the mapping file is equivalent to the implementation class of the interface.

 

 

 

 

 

Use of MyBatis dao layer

Introduce a mapping file in the mybatis global configuration file.

     InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();

        //Use mapper to call methods in the interface and manipulate the database
        //The parameter is a class object of the mapper interface class
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        //insert
        Student student1 = new Student();
        student1.setName("chy");
        mapper.insertStudent(student1);

        //query
        Student student2 = mapper.queryById(1);
        System.out.println(student2);

        sqlSession.commit();
        sqlSession.close();

 

 

 

 

 

Parameters passed in wrapper type

Sometimes we need to pass in multiple parameters, such as

  • Querying students with age > 20 and score > 90 requires passing in two Integer parameters
  • To query a book's sales this week, you need to pass in a pojo class: Book, and you need to pass in a parameter to represent the week or less.
  • To query the order information of a user purchasing a car, two pojo classes need to be passed in: User, Car

This situation of passing in multiple parameters is common in complex conditional queries, especially multi-table queries.

 

mybatis can only pass in at most one parameter, what can I do?

You can wrap the parameters you want to pass in, put them in a wrapper class, and pass them in.

 

 

Create a new package, com.chy.vo, and a new wrapper class, UserQueryVO, under the package. Write the incoming parameters as member variables, and provide getter, setter methods:

public class UserQueryVO {
    private User user;
    private Car car;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }
}

vo:value object value object

po:persist object Persists the object, corresponding to the data table.

pojo:plain ordinary java object Simple Java object

 

 

Create a new UserMapper interface under the com.chy.mapper package and write corresponding mapping files to implement database operations.

public interface UserMapper {
    public Order queryOrder(UserQueryVO vo);
}
<mapper namespace="com.chy.mapper.UserMapper">
    <select id="queryOrder" parameterType="com.chy.vo.UserQueryVO" resultType="com.chy.pojo.Order">
        SELECT * FROM order_tb WHERE order_tb.user_id=#{user.id} AND order_tb.car_name=#{car.name}
    </select>
</mapper>

The user and car in #{} are attributes of vo, and these two attributes are also objects themselves. You can access the attributes of user and car through.

 

 

Use:

     InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();

        Car car = new Car();
        car.setName("BMW X6");

        User user = new User();
        user.setId(1);

        //Wrapper class to pass in
        UserQueryVO vo = new UserQueryVO();
        vo.setCar(car);
        vo.setUser(user);


        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //Input wrapper class for query
        Order order = mapper.queryOrder(vo);
        System.out.println(order);

 

 

 

 

 

Pass in multiple parameters using Map

In addition to passing in multiple parameters using wrapper classes, you can also pass in multiple parameters using Map.

 

Mapper interface:

public interface UserMapper {
    public Order queryOrder(Map<String,Object> map);
}

This is the Mapper interface, so parameters usually write interfaces, not specific implementation classes, so the coupling is at the interface level.

The parameters to be passed in have different data types, written as Object s.

 

 

Mapping file:

<mapper namespace="com.chy.mapper.UserMapper">
    <select id="queryOrder" parameterType="HashMap" resultType="com.chy.pojo.Order">
        SELECT * FROM order_tb WHERE order_tb.user_id=#{user.id} AND order_tb.car_name=#{car.name}
    </select>
</mapper>

The user and car in #{} are the key s of the map, get the corresponding value (object), and then get the attribute value through.

 

 

Use:

     InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();

        Car car = new Car();
        car.setName("BMW X6");

        User user = new User();
        user.setId(1);

        //Wrapper class to pass in
        HashMap<String,Object> map = new HashMap<>();
        map.put("car", car);
        map.put("user", user);

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //Input map for query
        Order order = mapper.queryOrder(map);
        System.out.println(order);

 

It is simpler to use map without creating a vo class than to pass in multiple parameters using a wrapper class.

Tags: Java Mybatis xml Database

Posted on Mon, 06 Jan 2020 23:48:00 -0800 by deived