Mybatis使用@Mapper和@MapperScan注解实现映射关系

MyBatis与Spring整合后需要实现实体和数据表的映射关系。

实现实体和数据表的映射关系可以在Mapper类上添加@Mapper注解,如下代码:

/**
 * 用户信息Mapper动态代理接口
 * @author pan_junbiao
 **/
@Mapper
@Repository
public interface UserMapper
{
    /**
     * 新增用户,并获取自增主键
     */
    @Insert("INSERT INTO tb_user(user_account,user_password,blog_url,blog_remark) VALUES(#{userAccount},#{userPassword},#{blogUrl},#{blogRemark})")
    @Options(useGeneratedKeys = true, keyColumn = "user_id", keyProperty = "userId")
    //或者:@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyColumn = "user_id", keyProperty = "userId",before = false, resultType = Integer.class)
    public int insertUser(UserInfo userInfo);

    /**
     * 修改用户
     */
    @Update("UPDATE tb_user SET user_account = #{userAccount} ,user_password = #{userPassword} ,blog_url=#{blogUrl} ,blog_remark=#{blogRemark} WHERE user_id = #{userId}")
    public int updateUser(UserInfo userInfo);

    /**
     * 删除用户
     */
    @Delete("DELETE FROM tb_user WHERE user_id = #{userId}")
    public int deleteUser(int userId);

    /**
     * 根据用户ID,获取用户信息
     */
    @Select("SELECT * FROM tb_user WHERE user_id = #{userId}")
    public UserInfo getUserById(int userId);
}

但是建议以后直接在SpringBoot启动类中加 @MapperScan("com.pjb.mapper") 注解,这样会比较方便,不需要对每个Mapper都添加@Mapper注解。

package com.pjb;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
/**
 * SpringBoot启动类
 * @author pan_junbiao
 **/
@MapperScan("com.pjb.mapper")
@SpringBootApplication
public class SpringbootMybatisDemoApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
    }
}

 

你可能感兴趣的:(MyBatis,我の原创)