基于注解的Mybatis
1. 修改Dao类如下
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
}
2. 修改SqlMapConfig.xml如下,并移除对应Dao的xml文件
<!-- 告知 mybatis 映射配置的位置 -->
<mappers>
<mapper class="com.itheima.dao"/>
</mappers>
Mybatis 注解开发
常用注解
@Insert//:实现新增
@Update//:实现更新
@Delete//:实现删除
@Select//:实现查询
@Result//:实现结果集封装
@Results//:可以与@Result 一起使用,封装多个结果集
@ResultMap//:实现引用@Results 定义的封装
@One//:实现一对一结果集封装
@Many//:实现一对多结果集封装
@SelectProvider//: 实现动态 SQL 映射
@CacheNamespace//:实现注解二级缓存的使用
示例:
public class UserDao{
/**
*在实际开发中,会遇到实体属性名与表的列名不一致的情况,可以通过配置两者的对应关系来解决
*/
@Select("select * from user")
@Results(id="userMap",
value= {
@Result(id=true,column="id",property="userId"),
@Result(column="username",property="userName"),
@Result(column="sex",property="userSex"),
@Result(column="address",property="userAddress"),
@Result(column="birthday",property="userBirthday")
})
List<User> findAll();
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
/**
*插入成功后返回插入数据的ID,一般适合于自增id
*/
@Insert("insert into
user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address}
)")
@SelectKey(keyColumn="id",keyProperty="id",resultType=Integer.class,before =
false, statement = { "select last_insert_id()" })
int saveUser(User user);
}
/**
* 查询所有账户,采用延迟加载的方式查询账户的所属用户
*/
@Select("select * from account")
@Results(id="accountMap",
value= {
@Result(id=true,column="id",property="id"),
@Result(column="uid",property="uid"),
@Result(column="money",property="money"),
@Result(column="uid",
property="user",
one=@One(select="com.itheima.dao.IUserDao.findById",
fetchType=FetchType.LAZY)
)
})
List<Account> findAll();