Mybatis 常用注解及使用案例

2022-10-03 14:25:33

目录

Mybatis中常用的注解

使用案例

(1)@Select 简单查询

(2)@Insert 简单插入

(3)@Update 简单更新

(4)@Delete 简单删除

(5)@One

(6)@Many


Mybatis中常用的注解

注解目标对应的XML标签
@CacheNamespace<cache>
@CacheNamespaceRef<cacheRef>
@Results方法<resultMap>
@Result方法

<result>

<id>
@One方法<association>
@Many方法<collection>

@Insert

@Update

@Delete
方法

<insert>

<update>

<delete>

@InsertProvider

@UpdateProvider

@DeleteProvider

@SelectProvider
方法

<insert>

<update>

<delete>

<select>

允许创建动态SQL
@Param参数N/A
@Options方法映射语句的属性
@select方法<select>

使用案例

(1)@Select 简单查询

@Select(" Select * from user ")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "name", property = "name"),
            @Result(column = "tel", property = "tel"),
            @Result(column = "birth", property = "birth"),
            @Result(column = "address", property = "address")
    })
    List<User> queryAllUser();

(2)@Insert 简单插入

@Insert(" insert into user(name,sex,age) values(#{name},#{sex},#{age} " )
int saveUser(User user);

(3)@Update 简单更新

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

(4)@Delete 简单删除

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

(5)@One

@Select(" select * from user where id = #{id} ")
    @Results(
            value = {
                    @Result(column = "name",property = "name"),
                    @Result(column = "type",property = "type",
                    //one指示我们,查询出来的结果只有一个。
                    one = @One(select="com.xxxx.UserMapper.findTypeById",
                    //及时加载  
                    fetchType = FetchType.EAGER))
            }
    )
    User findUserById(Integer id);

(6)@Many

@Select(" select * from dept")
    @Results({
            @Result(id = true, column = "did", property = "did"),
            @Result(column = "name", property = "name"),
            @Result(column = "address", property = "address"),
            @Result(column = "id",property = "emps",
            //many指示我们,查询出来的结果有很多个
            many = @Many(
            //select = sql语句
            select = "com.xxxx.EmpMapper.findAllEmpByDid",
            //懒加载
            fetchType = FetchType.LAZY))
    })
    List<Dept> findAllDept();

转自:https://www.cnblogs.com/uiee/p/10778694.html

表示感谢!!!

@Results、@Result、@ResultMap注解的使用是为了解决实体类名称和数据库名称不一致的问题,使用方法参考如下博客:

参考:
https://www.cnblogs.com/voidchar/p/11277572.html

https://www.jianshu.com/p/b5f823ac5355

  • 作者:夏沐_lk
  • 原文链接:https://blog.csdn.net/guanmao4322/article/details/106302537
    更新时间:2022-10-03 14:25:33