延迟加载,一二级缓存,注解开发完善,以及用注解开发实现延迟加载,一对多,一对一,一二级缓存
一对一
要实现注解开发,首先创建一个普通maven项目,在pom.xml中加入所需的依赖,在数据库中有user和account表,创建两个实体类user和account,放在com.domain包中,两个实体类的字段分别对应数据库表中的列名,配置好sqlMapConfig.xml(别名,环境,映射),在com.dao中创建AccountDao, 如下
package com.dao;
import com.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
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 = "com.dao.UserDao.findById",fetchType = FetchType.EAGER))
})
List<Account> findAll();
//实际开发中,对一的选择直接加载,对多的选择延迟加载
@Select("select * from account where uid = #{uid}")
List<Account> findAccountByUid(Integer id);
}
以上就是注解开发,@select对应的就是xml文件映射的select标签,@Results对应的就是ResultMap标签,主键在@Result配置,一对一在于
@Result(property = "user",column = "uid",one = @One(select = "com.dao.UserDao.findById",fetchType = FetchType.EAGER))
一个账户对应一个用户,one属性中可以配置方法名的映射,要想通过account表中的uid查到user的信息,可以通过UserDao中的方法findById查到user的信息,然后封装至account实体中,所以,account实体中就有添加
//一对一,账户对用户
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
user的get和set,便于封装,再写一个测试类
@Test
public void findAll() throws Exception{
List<Account> accounts = accountDao.findAll();
for (Account account : accounts) {
System.out.println(account);
System.out.println(account.getUser());
}
}
查询account信息的同时,得到user的信息。
一对多
先在User实体类中添加多的account
//一对多
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
package com.dao;
import com.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
public interface UserDao {
/**
* 注解方式查询所有
* @return
*/
@Select("select * from user")
@Results(id = "userMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "birthday",property = "birthday"),
@Result(column = "sex",property = "sex"),
@Result(column = "address",property = "address"),
@Result(property = "accounts",column = "id",many = @Many(select = "com.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY))
})
List<User> findAll();
/**
* 通过id查询用户
* @param id
* @return
*/
@Select("select * from user where id = #{id}")
User findById(Integer id);
}
通过和实体类中定义的accounts字段对应,
@Result(property = "accounts",column = "id",many = @Many(select = "com.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY))
通过com.dao.AccountDao.findAccountByUid方法,查询到多的account信息