当前位置: 首页 > 工具软件 > Mybatis-Milu > 使用案例 >

【MyBatis】mybatis注解

宋嘉禧
2023-12-01

1. 增删改查注解

package com.dao;
import com.domain.User;
import org.apache.ibatis.annotations.*;

public interface IUserDao {
    //基本类型方法参数,占位符名字随便起
    @Select("select * from User where id =#{abc}")
    User findById(int id);

    //引用类型作为方法参数,占位符名字要跟该引用类型的属性名一致
    @Insert("insert into user values (null,#{username},#{age})")
    //新增数据后获取自增主键的值并封装进对象的主键属性中
    //keyProperty是封装值的属性名,resultType是返回值类型,Class类,before表示是否在insert前执行,statement是执行的sql语句
    @SelectKey(keyProperty = "id",resultType = Integer.class,before = false, statement = "select last_insert_id()")
    void save(User user);

    @Update("update user set username=#{username},age=#{age} where id=#{id}")
    void update(User user);

    @Delete("delete from user where id=#{id}")
    void delete(int id);
}

2. 多对一映射

//定义查询结果映射规则
//id是映射规则唯一名称,value是列与属性的对应关系
@Results(id="accountMap",value = {
        //property属性名,column列名,one是主表属性
        //One注解中的select是调用指定方法进行查询并把关联属性值映射进去
        //One注解中的fetchType是懒加载选项,可覆盖mybatis主配置文件的全局懒加载配置,即fetchType的值优先,
        // fetchType的值默认是立即加载, FetchType.LAZY可配置延迟加载
        @Result(property = "user",column = "userid",one=@One(select="com.dao.IUserDao.findById",fetchType = FetchType.LAZY))
})
@Select("select * from account")
//在方法上面定义的@Results,该方法要省略@ResultMap引用
//@ResultMap("accountMap")
List<Account> findAll();

//下面一对多映射需要调用的方法
@Select("select * from account where userid=#{userid}")
List<Account> findByUserid(int userid);

3.一对多映射

@Results(id="userMap",value = {
        //必须声明主键,否则会被下面的column覆盖掉,主键值会变NULL
        //id是否主键,property属性名,column列名,many是从表集合属性
        @Result(id=true,property = "id",column = "id"),

        //Many注解中的select是调用指定方法进行查询并把关联属性值映射进去
        //这里的column表示传递给查询方法的参数列的名称 ,这里的column值跟上面主键列冲突
        //Many注解中的fetchType是懒加载选项,默认值是mybatis主配置文件的全局懒加载配置,
        // FetchType.LAZY配置延迟加载,FetchType.EAGER立即加载
        @Result(property = "accountList",column = "id",many=@Many(select="com.dao.IAccountDao.findByUserid",fetchType = FetchType.LAZY))
})
@Select("select * from user")
List<User> findAll();
 类似资料: