mybatis 注解开发,常用配置
实体类字段:userId,userName,userBirthday,userSex,userAddress
表字段:id,username,birthday,sex,address
mybatis实体类的属性名和数据库表的列名对应不上
@Select("select * from user")
@Results(id = "userMap",value={
@Result(id=true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "birthday",property = "userBirthday"),
@Result(column = "sex",property = "userSex"),
@Result(column = "address",property = "userAddress")
)
})//解决数据库表列名和实体类属性不一致
List<User> findAllUser();
mybatis多表操作
user实体类字段:id,username,birthday,sex,address
user表字段:id,username,birthday,sex,address
accout实体类字段:id,uid,money
accout表字段:ID,UID,MONEY
user表与accout表通过accout表的UID关联
一对一操作
从表实体包含主表实体的对象引用实现多表查询
实体类
public class Account implements Serializable {
private static final long serialVersionUID = -572002165576836918L;
private int id;
private int uid;
private double money;
/**
* 从表实体包含主表实体的对象引用实现多表查询
*/
private User user;
......
}
AccountDao接口
public interface AccountDao {
/**
* 查询所有账户
* @return
*/
@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(property = "user",column = "uid",
one = @One(
select="cn.td.dao.UserDao.findUserById",
fetchType = FetchType.EAGER)
)
})
List<Account> findAllAccount();
}
UserDao接口
public interface UserDao {
/**
* 通过id查询用户信息
* @param id 用户id
* @return 用户信息
*/
@Select("select * from user where id = #{id}")
@ResultMap(value = {"userMap"})
User findUserById(int id);
}
一对多操作
实体类
public class User implements Serializable {
private static final long serialVersionUID = -1460860200295772773L;
private int userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
//一对多关系映射:主表实体包含从表实体的集合引用
private List<Account> accounts;
......
}
UserDao接口
public interface UserDao {
/**
* 查询所有用户
* @return 查询的结果集
*/
@Select("select * from user")
@Results(id = "userMap",value={
@Result(id=true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "birthday",property = "userBirthday"),
@Result(column = "sex",property = "userSex"),
@Result(column = "address",property = "userAddress"),
@Result(column ="id",property = "accounts",
many = @Many(
select = "cn.td.dao.AccountDao.findAccountById",
fetchType = FetchType.LAZY //配置延迟加载
)
)
})
List<User> findAllUser();
}
AccountDao接口
public interface AccountDao {
/**
* 通过用于ID查询账户信息
* @param uid
* @return
*/
@Select("select * from account where uid = #{uid}")
List<Account> findAccountById(Integer uid);
}
开启二级缓存
在要开启二级缓存的DAO接口上配置@CacheNamespace注解
@CacheNamespace(blocking = true)//开启二级缓存
public interface UserDao {
.......
}