查
查询中携带参数
使用注解
注解实现,就不需要写mapper的interface的实现类了
接口中的函数可以和mapper里面的<select>
中的参数一一对应,
当然也可以和注解一一对应
@Select("select * from user where username = #{name}")
List<User> findUserByName(String name);
不过mybatis里面的config,mappers文件的映射文件,就不是映射到resources里面的文件了,这些文件已经没有用了!
映射到接口就行了,注解相当于mapper,注解即可实现
<!--映射配置文件-->
<mappers>
<!--<mapper resource="com/kcl/dao/UserMapper.xml"/>-->
<mapper class="com.kcl.dao.UserDao"/>
</mappers>
改
根据用户id,修改用户的信息,参数是User
void updateUserById(User user);
<update id="updateUserById" parameterType="com.kcl.pojo.User">
update user set
username = #{username},birthday = #{birthday},sex = #{sex},address = #{address}
where id = #{id}
</update>
当然也可以写成注解的方式
@Update("update user set
username = #{username},birthday = #{birthday},sex = #{sex},address = #{address} where id = #{id}")
void updateUserById(User user);
增
date需要单独处理哦
void addUser(User user);
<insert id="addUser" parameterType="com.kcl.pojo.User">
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
</insert>
当然也可以写注解
@Insert("insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})")
void addUser(User user);
删
void deleteByUserName(String name);
<delete id="deleteByUserName" parameterType="String">
delete from user where username = #{name}
</delete>
使用注解的方式
@Delete("delete from user where username = #{name}")
void deleteByUserName(String name);
注解进阶
当使用了注解,又生成了Dao.xml文件,无论是否使用该xml文件,mybatis运行时都报错!!!
注解实体类属性和表中的对应关系
results参数中传递一个数组
results根据id可以给其他进行使用
@Select("select * from user")
@Results(id = "userMap",value = {
@Result(id = true, property = "id", column = "id"),
@Result(property = "id", column = "id"),
@Result(property = "userName", column = "username"),
@Result(property = "sex", column = "sex"),
@Result(property = "birthday", column = "birthday"),
@Result(property = "myAddress", column = "address")
}
)
List<User> findAll();
注解一对一
一个账户对应一个用户
@Select("select * from account")
@Results(id="accountMap",
value = {
@Result(id = true, property = "id" , column = "id"),
@Result(property = "uid", column = "uid"),
@Result(property = "money", column = "money"),
//column 表示子查询传递的参数
@Result(property = "user", column = "uid",one=@One(select = "com.kcl.dao.UserDao.findById",fetchType = FetchType.EAGER))
}
)
List<Account> findAll();
注解一对多
一个用户包含多个账户
@Select("select * from user")
@Results(id = "userMap",value = {
@Result(id = true, property = "id", column = "id"),
@Result(property = "id", column = "id"),
@Result(property = "userName", column = "username"),
@Result(property = "sex", column = "sex"),
@Result(property = "birthday", column = "birthday"),
@Result(property = "myAddress", column = "address"),
// 查询出来一行一行,每个id都有一个集合,然后存放
// column不能省略
@Result(property = "accounts", column = "id",
many = @Many(
select = "com.kcl.dao.AccountDao.findById",
fetchType = FetchType.LAZY
))
}
)
List<User> findAll();
注解使用二级缓存
cacheEnabled 默认是true,不配置也可以
@CacheNamespace(blocking = true)
public interface UserDao {
}