注解开发MyBatis

157 阅读2分钟
  • 使用注解书写SQL其实是对使用XML书写SQL的一种替代方式,其功能基本一致。

  • 常用注解

    • @Select(“查询的 SQL 语句”):执行查询操作注解
    • @Insert(“新增的 SQL 语句”):执行新增操作注解
    • @Update(“修改的 SQL 语句”):执行修改操作注解
    • @Delete(“删除的 SQL 语句”):执行删除操作注解

单表

//查
@Select("select * from emp")
List<Emp> selectAll();

//根据id查
@Select("select * from emp where id=#{selectID}")
Emp selectById(@Param("selectID") Integer id);
//添加
/*
返回主键自增
useGeneratedKeys:是否使用创建的主键。
keyColumn:数据表中的列名。
keyProperty:类中的属性名。
*/
@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
@Insert("INSERT INTO `emp` VALUES ( #{id},#{ename},#{sex},#{salary},#{address})")
void add(Emp emp);

//删除
@Delete("DELETE FROM `emp` WHERE `id`=#{id}")
void delete(Integer id);

//修改
@Update("update `emp` " +
        "set `ename`=#{ename},`sex`=#{sex},`salary`=#{salary},`address`=#{address}" +
        " where `id`=#{id}" )
void update(Emp emp);

多表

图下代码会栈内存溢出,把两个实体类方法toString注释掉就好了

public interface TblUserMapper {
    //查所有
    /*
    * @Results:封装映射关系的父注解:相当于<resultMap>
    *   id:相当于<resultMap>的id属性
    *   value:要映射的内容(数据库查询结果的字段与实体类的属性名称)
    * @Result:封装映射关系的子注解:相当于result
    *       column 属性:查询出的表中字段名称
            property 属性:实体对象中的属性名称
            javaType 属性:被包含对象的数据类型
            one 属性:一对一查询固定属性
            many 属性:一对多查询固定属性
     */
    @Results(id = "TblUserResult",value = {
            @Result(id = true,column = "id", property = "id"),//id:<id>,代表主键
            @Result(column = "username", property = "username"),
            @Result(column = "password", property = "password"),
            @Result(column = "sex", property = "sex"),
            @Result(column = "email", property = "email"),
            @Result(column = "telephone", property = "telephone"),
            @Result(column = "id",
                    /*
                    @Many:一对多查询的注解。
                        select 属性:指定调用某个接口中的方法
                    */
                    many = @Many(select = "com.eponine.dao.TblAccountMapper.selectByUid"),
                    property = "accounts")
    })
    @Select("SELECT id,username,password,sex,email,telephone FROM `TblUser`")
    List<TblUser> selectAll();

    //根据id查
    @ResultMap("TblUserResult")//使用上面的结果集
    @Select("SELECT * FROM `TblUser` where id=#{id}")
    TblUser selectById(Integer id);
}
public interface TblAccountMapper {
    //根据id查
    @Results(id = "TblAccountResult",value = {
            @Result(column = "aid",property = "aid"),
            @Result(column = "money",property = "money"),
            @Result(column = "address",property = "address"),
            @Result(column = "aname",property = "aname"),
            @Result(column = "uid",property = "uid"),
            @Result(column = "uid",
                    /*@One:一对一查询的注解。
                            select 属性:指定调用某个接口中的方法*/
                    one = @One(select = "com.eponine.dao.TblUserMapper.selectById"),
                    property = "user")}
    )
    @Select("SELECT aid,money,address,aname,uid" +
            " FROM tblaccount" +
            " WHERE uid=#{value}")
    List<TblAccount> selectByUid(Integer uid);

    //查询所有
    @ResultMap("TblAccountResult")
    @Select("SELECT * FROM tblaccount")
    List<TblAccount> selectAll();
}

分页查询

SqlSession sqlSession = MyBatisUtils.getSqlSession();
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
//分页查询
/*分页API:
 *      在获取mapper之后,在查询之前
 *      PageHelper.startPage(1,5);   当前第1页,每页显式5条数据
 *      之后只需要查询所有,就不再是查询所有了,就是按分页查询这一页的数据了!!
 *      将这一页的数据封装PageInfo对象,方便页面最终获取数据*/
//分页操作
PageHelper.startPage(1,5);
//分页查询
List<Emp> emps = mapper.selectAll();
//封装对象
PageInfo<Emp> empPageInfo = new PageInfo<>(emps);
System.out.println(empPageInfo);