Java Web Learning Notes - mybatis-07-dao development and use (mapper agent development)

Need to write mapper interface (equivalent to dao interface)
mapper.xml mapping file needs to be written
mybatis can automatically generate proxy objects of mapper interface implementation classes

Development specification
1. namespace in mapper.xml is equal to the address of mapper interface
2. The method name in the interface is the same as the id name of the statement in mapper.xml
3. The method input parameter type of the interface is the same as that specified by the parameterType of the statement in mapper.xml
4. The method return value type of interface is consistent with the specified type of resultType of statement in mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<!--Use mappper Proxy method, namespace It plays an important and special role-->
<mapper namespace="com.sws.mapper.UserMapper">
    <select id="findUserByID" parameterType="int" resultType="com.sws.entity.User">
          select * from user where id = #{id}

    <select id="findUserByName" parameterType="java.lang.String" resultType="com.sws.entity.User">
        --SELECT * from user where username like #{username}
          select * from user where name like '%${username}%'

    <insert id="insertUser" parameterType="com.sws.entity.User">

        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select last_insert_id()
        insert into user(id,username,birthday,sex,address) value (#{id},#{username},#{birthday},#{sex},#{address})
    <!--delete user-->
    <delete id="deleteUser" parameterType="java.lang.Integer">
        delete  from user where id = #{id}
    <!--Update users-->
    <update id="updateUser" parameterType="">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id = #{id}
//Configure under SqlMapConfig.xml
    <mapper source="UserMapper.xml" />
//mapper interface writing must meet the development specifications
public interface UserMapper {
    public User findUserByID(int id) throws Exception;

    public void insertUser(User user) throws  Exception;

    public void deleteUser(int id)throws Exception;
//Call sqlsession
SqlSession sqlSession = sqlSessionFactory.openSession();
//Create the UserMapper object, and mybatis automatically generates the mapper proxy object
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//Call userMapper method
User user = userMapper.findUserByID(1);

mapper interface method parameters can only have one. You can use pojo of wrapper type to meet different types of method requirements

Keywords: xml Java Mybatis encoding

Added by Zomie on Fri, 01 May 2020 01:27:37 +0300