Mybatis CRUD

Mybatis CRUD

add data<insert>

  • When adding data, mybatis returns the number of affected rows by default, so there is no need to specify the ResultTypespecified return type
  • UserMapper.javaadd method to interface
/**
    @param user User对象
*/
Integer reg(User user);  
  • UserMapper.xmladd <insert>node to file

  • #{}Filled in is Userthe property name of the object

<!-- 节点名称取决于需要执行的操作 -->
    <!-- 例如增加操作应该使用insert节点 -->
    <!-- id属性(*)的值是Java接口中的方法名称 -->
    <!-- parameterType属性的值是参数类型 
    -->
    <!-- 节点中间编写SQL语句 -->
    <insert id="reg"
        parameterType="cn.tedu.spring.entity.User">
        INSERT INTO user (
            username, password
        ) VALUES (
            #{username}, #{password}
        )
    </insert>
  • test
@Test
    public void testReg() {
        //加载Spring的配置文件
        AbstractApplicationContext ac
            = new ClassPathXmlApplicationContext(
                "spring-mvc.xml",
                "spring-dao.xml");
        
        //获取UserMapper的bean,这个是spring通过扫描mapper.xml文件自动为mybatis自动创建的,首字母小写
        UserMapper userMapper
            = ac.getBean(
                "userMapper", UserMapper.class);
        
        //新建User对象
        User user = new User();
        user.setUsername("Tom1");
        user.setPassword("123456");
        
        //调用reg(user),进行添加,返回的是受影响的行数
        Integer affectedRows
            = userMapper.reg(user);
        
        System.out.println(
            "affectedRows=" + affectedRows);
        ac.close();
    }

Get the id of the auto-incrementing primary key when adding data in Mybatis

  • First of all mybatis, when processing the function of adding data, it just returns 受影响的行数, so the newly added data will not be returned in the persistence layer.
  • If you need to get the auto-incrementing primary key Id, first, you need to add an attribute to the XMLmapped <insert>node2
  • useGeneratedKeys: Set whether to return the auto-incrementing primary key, if trueso, return it, the default isfalse
  • keyProperty: Configure the fields corresponding to the auto-increment primary key in the table, because sometimes the fields of the auto-increment primary key in the table may not be id, so you need to specify
    <!-- 节点名称取决于需要执行的操作 -->
    <!-- 例如增加操作应该使用insert节点 -->
    <!-- id属性(*)的值是Java接口中的方法名称 -->
    <!-- parameterType属性的值是参数类型 
        useGeneratedKeys: 指定是否返回自增主键,默认为false
        keyProperty:配置自增主键在表中对应的字段 
    -->
    <insert id="reg"
        parameterType="cn.tedu.spring.entity.User" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO user (
            username, password
        ) VALUES (
            #{username}, #{password}
        )
    </insert>
  • After the mybatisexecution insertmethod at this time, it is called reg(user)and returned 受影响的行数, not the value of the self-incrementing primary key at this time id. But when this method is called, it will be idencapsulated into the specified 方法参数, that is, encapsulated into userit, so only the caller can get idit, but the persistence layer cannot get it.
    @Test
    public void testReg() {
        //加载Spring的配置文件
        AbstractApplicationContext ac
            = new ClassPathXmlApplicationContext(
                "spring-mvc.xml",
                "spring-dao.xml");
        
        //获取UserMapper的bean,这个是spring通过扫描mapper.xml文件自动为mybatis自动创建的,首字母小写
        UserMapper userMapper
            = ac.getBean(
                "userMapper", UserMapper.class);
        
        //新建User对象,此时并没有设置id的值
        User user = new User();
        user.setUsername("Tom1");
        user.setPassword("123456");
        
        //调用reg(user),进行添加,返回的是受影响的行数,但是此时已经将id封装到参数User对象中了
        Integer affectedRows
            = userMapper.reg(user);
        
        System.out.println(
            "affectedRows=" + affectedRows);
        //直接获取Uesr对象中的id值,这个是自增主键返回的值
        System.out.println("id = "+user.getId());
        ac.close();
    }

delete data<delete>

  • When deleting data, the number of affected rows will be automatically returned. There is no need deleteto define the return type in the node. The return type will only be defined when querying data.

  • UserMapper.javaAdd an interface method in

    //根据id删除数据,返回受影响的行数,返回1,如果删除失败返回0
    Integer deleteUserById(int id);
  • UserMapper.xmlconfigure <delete>node in
    <!-- 删除用户数据根据id
        Integer deleteUserById(int id)
        parameterType: 指定参数类型,这里也可以不需要指定
     -->
    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>   
  • Deleting data is irreversible. Usually, data is not really deleted. We will use backups, logs and other means to save data. Deletes seen in many software may be 修改operations. Usually, there is a field in the table to is_deletedmark whether to delete or not. If the deletion is performed, then its value will be set to trueindicate that it has been deleted, then it will not be displayed on the client at this time, making the client think that it has been deleted.

Mybaits parameter rules

  • mybatisBy default, one parameter is supported, that is, there can only be one parameter in the defined interface method.
  • If you need to support multiple parameters, you need to use @Param()annotations
  • If the parameter type in the interface method is a basic type, the parameterTypespecified type can be omitted. If it is not a basic type, the specification requires the parameterTypespecified type to be used, but it is not necessary to write

@Param()

  • mybatis supports one parameter by default, that is, there can only be one parameter in the defined interface method
  • When designing a java interface method, if you need to specify multiple parameters, you must use@Param()
  • If you want to support multiple parameters, you need to use @Param()to specify the parameters, such asInteger ChangePassword(@Param("id")Integer id,@Param("newPassword")String newPassword);
  • Among them @Param("key"), expressions are used to extract valuewhen configuring additions, deletions, and changes .#{key}
  • mybaitsIn the process of processing, the parameters are essentially Mapencapsulated. That is @Param(""), the parameter value given in the annotation is medium, the parameter value Mapgiven keywhen calling the method is the value in the Map value, and the final XMLuse of the obtained value in the file is #{}actually obtained by using the get(key)method in the Map

change the data<update>

  • When modifying data, mybatis automatically returns the number of affected rows, so we do not need to define the return type, the default return data is the number of affected rows

  • Define methods in the UserMapper.javainterface that idmodify data based on

  • Use @Param()annotations to mark multiple parameters

    /**
     * 修改密码
     * @param id  id
     * @param newPassword  新密码
     * @return  受影响的行数
     */
    Integer ChangePassword(@Param("id")Integer id,@Param("newPassword")String newPassword);
  • UserMapper.xmladd <update>node in

  • where #{}the fields in the expression are @Param("value")invalue

    <!-- 修改密码
        Integer ChangePassword(@Param("id")Integer id,@Param("newPassword")String newPassword);
     -->
    <update id="ChangePassword">
        update user set password=#{newPassword} where id=#{id}
    </update>   
  • testing method
    @Test
    public void testChangePassword() {
        //加载Spring的配置文件
        AbstractApplicationContext ac
            = new ClassPathXmlApplicationContext(
                "spring-mvc.xml",
                "spring-dao.xml");
        
        //获取UserMapper的bean,这个是spring通过扫描mapper.xml文件自动为mybatis自动创建的,首字母小写
        UserMapper userMapper
            = ac.getBean(
                "userMapper", UserMapper.class);
        //调用删除的方法
        int affectRow=userMapper.ChangePassword(3, "12345895");
        System.out.println(affectRow);
        ac.close();
    }

Case: Change User Password

User provided data

  • Old Password:oldPassword
  • new password:newPassword

step

  1. By idlooking up user information
  2. Can not be used select * from user where id=? and password=?, because this is case- insensitive , we should first idobtain user information, and then comparepassword
  3. Complete the verification logic in UserserviceImpl, if the user does not exist, throw an exception that the user does not exist, and if it exists, verify whether the original password matches the
  4. If the user information exists, then it is necessary to verify whether the user input is oldPasswordthe same as the user information. 原密码If it is not the same, throw it out 密码不匹配的异常. If it is the same, then the password can be changed.
  5. change Password

accomplish

  • We wrote a UserServicelogic written in
    public void ChangePasssword(Integer id, String oldPassword,
            String newPassword) throws UserNotFoundException, PasswordNotMatchException{
        User user=this.findUserById(id);  //获取用户信息
        if (user==null) {   //如果用户信息不存在
                throw new UserNotFoundException("操作失败,用户信息不存在");
        }else { //用户存在,则判断原密码
            if (user.getPassword().equals(oldPassword)) {//如果密码匹配
                
                userMapper.ChangePassword(id, newPassword);  //修改密码
            }else {   //原密码不匹配
                    throw new PasswordNotMatchException("操作失败,原密码不正确");
            }
        }
    }
  • Then Controllerif you want to call this in , it ChangePassswordwill judge what went wrong by handling the exception, and give a friendly prompt

Query data<select>

Query for a single piece of data

  • The idquery result returned by the query is a single piece of data, such as:select * from user where id=1
  • When writing a query for a single record , you 接口方法only need to return one实体类对象
    /**
     * 根据id查询用户信息
     * @param id  用户id
     * @return 返回User对象
     */
    User findUserById(Integer id);
  • UserMapper.xmlconfigure <select>node in
  • The specified return type needs to be used resultType, because the parameter is a primitive type, so there is no need to use the parameterTypespecified parameter type
    <select id="findUserById" resultType="cn.tedu.spring.entity.User">
        select * from user where id=#{id}
    </select>

Find multiple records

  • Some lookup statements return multiple records, so we can use the List<>collection to receive the returned results, but not directly 实体类对象.
  • UserMapper.javadefine interface methods in
    /**
     * 根据密码查找用户
     * @param password 用户密码
     * @return 返回的是一个用户的集合
     */
    List<User> findUserByPassword(String password); 
  • UserMapper.xmladd <select>node in
  • resultTypeAlthough the return here is User集合, but the type here still needs to write the User type
  • Since the parameter is a primitive type, there is no need to useparameterType
    <!-- 
        List<User> findUserByPassword(String password);
        resultType: 虽然返回的是User集合,但是这里的类型还是需要写User类型
     -->
     
     <select id="findUserByPassword" resultType="cn.tedu.spring.entity.User">
        select * from user where password=#{password}
     </select>
  • test
    @Test
    public void testFindUserByPassword() {
        //加载Spring的配置文件
        AbstractApplicationContext ac
            = new ClassPathXmlApplicationContext(
                "spring-mvc.xml",
                "spring-dao.xml");
        
        //获取UserMapper的bean,这个是spring通过扫描mapper.xml文件自动为mybatis自动创建的,首字母小写
        UserMapper userMapper
            = ac.getBean(
                "userMapper", UserMapper.class);
        //获取User集合
        List<User> users=userMapper.findUserByPassword("12345895");
        System.out.println(users);
        ac.close();
    } 

Summarize

  1. xxMapper.xmlThe nodes configured in idmust be xxMapper.javathe 方法名same as in
  2. mybatis supports one parameter by default, but we can use to @Param("")specify multiple parameters, but when using #{}the value, it must be @Param("")consistent with the parameters in
  3. Obtaining the self-incrementing primary key is not used as the return value of the method, but when the method is called, the value of the self-incrementing primary key is set in the object of the method parameter, then the caller at this time can get 自增主键the value.
  4. Add, modify, delete, the method returns always the number of affected rows
  5. ** When defining entity class attributes, try to use them 包装类, such asInteger age**
  6. As long as it is a <select>node, the return type must be written resultType, whether it is a basic type or another type

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325913118&siteId=291194637