Mybatis中的延迟加载
<!-- 配置参数 -->
<settings>
<!-- 开启Mybatis支持延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"></setting>
</settings>
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的主配置文件 -->
<configuration>
<!-- 配置properties 可以在标签内部配置连接数据库信息,也可以通过属性引用外部配置文件 -->
<properties resource="jdbcConfig.properties"></properties>
<!-- 配置参数 -->
<settings>
<!-- 开启Mybatis支持延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"></setting>
</settings>
<!-- 使用typeAliases配置别名,只能配置domain中类的别名-->
<typeAliases>
<package name="com.itcase.domain"></package>
</typeAliases>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置mysql环境 -->
<environment id="mysql">
<!-- 配置事务的类型 -->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源(连接池)-->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
<mappers>
<package name="com.itcase.dao"></package>
</mappers>
</configuration>
user.java
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
// 一对多关系映射:主表尸体应该包含从表实体的集合应用
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
Account.java
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
// 从表实体应该包含一个主实体的对象引用
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}
IUserDao接口
public interface IUserDao {
// 查询所有用户
List<User> findAll();
// 根据id查询用户信息
User findById(Integer userId);
}
IAcoountDao接口
public interface IAccountDao {
// 查询所有
List<Account> findAll();
// 根据用户id查询账户信息
List<Account> findAccountByUid(Integer uid);
}
IUserDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itcase.dao.IUserDao">
<!-- 定义封装User和resultMap-->
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"></id>
<result column="username" property="username"></result>
<result column="address" property="address"></result>
<result column="sex" property="sex"></result>
<result column="birthday" property="birthday"></result>
<!-- 一对多的关系映射:配置user对象中accounts集合的映射 -->
<collection property="accounts" ofType="account" select="com.itcase.dao.IAccountDao.findAccountByUid" column="id"></collection>
</resultMap>
<!-- 查询所有-->
<select id="findAll" resultMap="userAccountMap">
select * from user
</select>
<!-- 根据id查询用户 -->
<select id="findById" parameterType="INT" resultType="user">
select * from user where id = #{uid};
</select>
</mapper>
IAccountDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itcase.dao.IAccountDao">
<!-- 定义封装account和resultMap-->
<resultMap id="accountUserMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!-- 一对一的关系映射:配置封装user内容
select属性指定的内容:查询用户的唯一标识:
column属性指定的内容:用户根据id查询时,所需要的参数的值
-->
<association property="user" column="uid" javaType="user" select="com.itcase.dao.IUserDao.findById"></association>
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultMap="accountUserMap">
select * from account
</select>
<!-- 根据用户id查询账户信息 -->
<select id="findAccountByUid" resultType="account">
select * from account where uid = #{uid}
</select>
</mapper>
UserTest.java
public class UserTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
@Before // 测试方法之前执行
public void init() throws Exception{
// 1、读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 2、获取SQLSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 3、获取SqlSessiond对象
sqlSession = factory.openSession(true);
// 4、获取dao得代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After // 测试方法之后执行
public void destroy() throws Exception{
// 提交事务
// sqlSession.commit();
// 6、释放资源
sqlSession.close();
in.close();
}
// 测试查询所有
@Test
public void testFindAll() {
List<User> users = userDao.findAll();
}
AccountTest.java
public class AccountTest {
private InputStream in;
private SqlSession sqlSession;
private IAccountDao accountDao;
@Before // 测试方法之前执行
public void init() throws Exception{
// 1、读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 2、获取SQLSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 3、获取SqlSessiond对象
sqlSession = factory.openSession(true);
// 4、获取dao得代理对象
accountDao = sqlSession.getMapper(IAccountDao.class);
}
@After // 测试方法之后执行
public void destroy() throws Exception{
// 提交事务
// sqlSession.commit();
// 6、释放资源
sqlSession.close();
in.close();
}
// 测试查询所有
@Test
public void testFindAll() {
// 5、执行查询所以方法
List<Account> accounts = accountDao.findAll();
}
}
Mybatis中的缓存
什么是缓存:存在于内存中的临时数据。
为什么使用缓存:减少和数据库的交互次数,提高执行效率。
适用于缓存:
经常查询并且不经常改变的。
数据的正确与否对最终结果影响不大的。
不适用于缓存:
经常改变的数据
数据的正确与否对最终结果影响很大的。
例如:商品的库存,银行的汇率,股市的牌价。
Mybatis中的一级缓存和二级缓存
一级缓存:
它指的是Mybatis中SqlSession对象的缓存。
当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供一块区域中。
该区域的结构是一个Map。当我们再次查询同样的数据,mybatis会先去sqlsession中查询是否有,有的话直接拿出来用。
当SqlSession对象消失时,mybatis的一级缓存也就消失了。
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
// 用户的持久层接口
public interface IUserDao {
// 查询所有用户
List<User> findAll();
// 根据id查询用户信息
User findById(Integer userId);
// 更新用户
void updateUser(User user);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itcase.dao.IUserDao">
<!-- 查询所有-->
<select id="findAll" resultType="user">
select * from user
</select>
<!-- 根据id查询用户 -->
<select id="findById" parameterType="INT" resultType="user">
select * from user where id = #{uid};
</select>
<!-- 更新用户信息 -->
<update id="updateUser" parameterType="user">
update user set username=#{username},address=#{address} where id=#{id}
</update>
</mapper>
public class UserTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
private SqlSessionFactory factory;
@Before // 测试方法之前执行
public void init() throws Exception{
// 1、读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 2、获取SQLSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
// 3、获取SqlSessiond对象
sqlSession = factory.openSession(true);
// 4、获取dao得代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After // 测试方法之后执行
public void destroy() throws Exception{
// 提交事务
// sqlSession.commit();
// 6、释放资源
sqlSession.close();
in.close();
}
// 测试一级缓存
@Test
public void testFirstLevelCache() {
User user1 = userDao.findById(41);
System.out.println(user1);
// sqlSession.close();
// 再次获取sqlSession对象
// sqlSession = factory.openSession();
sqlSession.clearCache(); // 此方法也可以清空缓存
userDao = sqlSession.getMapper(IUserDao.class);
User user2 = userDao.findById(41);
System.out.println(user2);
System.out.println(user1 == user2);
}
// 测试缓存同步
@Test
public void testClearlCache(){
// 1、根据id查询用户
User user1 = userDao.findById(41);
System.out.println(user1);
// 2、跟新用户信息
user1.setUsername("莉莉丝");
user1.setAddress("四川");
userDao.updateUser(user1);
// 3、再次查询id为41的用户
User user2 = userDao.findById(41);
System.out.println(user2);
System.out.println(user1 == user2);
}
}
二级缓存:
它指的是Mybatis中SqlSessionFactory对象的缓存。由同一个SqlSessionFactory对象创建的SqlSession共享其缓存。
二级缓存的使用步骤:
第一步:让Mybatis框架支持二级缓存(在SqlMapConfig.xml中配置)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的主配置文件 -->
<configuration>
<!-- 配置properties 可以在标签内部配置连接数据库信息,也可以通过属性引用外部配置文件 -->
<properties resource="jdbcConfig.properties"></properties>
<!-- 配置参数 -->
<settings>
<!-- 开启Mybatis支持二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 使用typeAliases配置别名,只能配置domain中类的别名-->
<typeAliases>
<package name="com.itcase.domain"></package>
</typeAliases>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置mysql环境 -->
<environment id="mysql">
<!-- 配置事务的类型 -->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源(连接池)-->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
<mappers>
<package name="com.itcase.dao"></package>
</mappers>
</configuration>
第二步:让当前的映射文件支持二级缓存(在IUserDao.xml中配置)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itcase.dao.IUserDao">
<!-- 开启user支持二级缓存 -->
<cache/>
<!-- 查询所有-->
<select id="findAll" resultType="user">
select * from user
</select>
<!-- 根据id查询用户 -->
<select id="findById" parameterType="INT" resultType="user" useCache="true">
select * from user where id = #{uid};
</select>
<!-- 更新用户信息 -->
<update id="updateUser" parameterType="user">
update user set username=#{username},address=#{address} where id=#{id}
</update>
</mapper>
第三步:让当前的操作支持二级缓存(在select标签中配置)
public class SecondLevelCacheTest {
private InputStream in;
private SqlSessionFactory factory;
@Before // 测试方法之前执行
public void init() throws Exception{
// 1、读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 2、获取SQLSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
}
@After // 测试方法之后执行
public void destroy() throws Exception{
in.close();
}
// 测试二级缓存
@Test
public void testFirstLevelCache() {
SqlSession sqlSession1 = factory.openSession(true);
IUserDao userDao1 = sqlSession1.getMapper(IUserDao.class);
User user1 = userDao1.findById(41);
System.out.println(user1);
sqlSession1.close(); // 一级缓存消失
SqlSession sqlSession2 = factory.openSession(true);
IUserDao userDao2 = sqlSession2.getMapper(IUserDao.class);
User user2 = userDao2.findById(41);
System.out.println(user2);
sqlSession2.close();
System.out.println(user1 == user2);
}
}
Mybatis中的注解开发
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 引入外部配置文件 -->
<properties resource="jdbcConfig.properties"></properties>
<!-- 配置别名 -->
<typeAliases>
<package name="com.itcase.domain"></package>
</typeAliases>
<!-- 配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 指定带有注解的dao接口所在位置 -->
<mappers>
<!-- <package name="com.itcase.dao"></package>-->
<mapper class="com.itcase.dao.IUserDao"></mapper>
</mappers>
</configuration>
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
// 在mybatis中针对CRUD一共有四个注解:@SelectT @Insert @Update @Delete
public interface IUserDao {
// 查询所有用户
@Select("select * from user")
List<User> findAll();
// 保存用户
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);
// 更新用户
@Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
void updateUser(User user);
// 删除用户
@Delete("delete from user where id=#{id}")
void deleteUser(Integer userId);
// 根据条件查询
@Select("select * from user where id=#{id}")
User findById(Integer userId);
// 根据用户名称模糊查询
// @Select("select * from user where username like #{username}")
@Select("select * from user where username like '%${value}%' ")
List<User> findUserByName(String username);
// 查询用户总数
@Select("select count(*) from user")
int findTotalUser();
}
public class MybatisAnnoTest {
// 测试基于注解的mubatis使用
public static void main(String[] args) throws Exception{
// 1、获取字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 2、根据字节输入流构建SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 3、根据SqlSessionFactory生产一个Sqlsession
SqlSession session = factory.openSession();
// 4、使用Sqlsession获取Dao的代理对象
IUserDao userDao = session.getMapper(IUserDao.class);
// 5、执行Dao的方法
List<User> users = userDao.findAll();
for (User user : users){
System.out.println(user);
}
// 6、释放资源
session.close();
in.close();
}
}
public class AnnotationCRUDTest {
private SqlSessionFactory factory;
private SqlSession session;
private InputStream in;
private IUserDao userDao;
@Before
public void init() throws Exception {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(IUserDao.class);
}
@After
public void dastroy() throws Exception {
session.commit();
session.close();
in.close();
}
@Test
public void testSave(){
User user = new User();
user.setUsername("王六");
user.setAddress("上海");
userDao.saveUser(user);
}
@Test
public void testUpdate(){
User user = new User();
user.setId(50);
user.setUsername("王五");
user.setAddress("南京");
user.setSex("男");
user.setBirthday(new Date());
userDao.updateUser(user);
}
@Test
public void testUDelete(){
userDao.deleteUser(51);
}
@Test
public void testFindOne(){
User user =userDao.findById(49);
System.out.println(user);
}
@Test
public void testFindByName(){
// List<User> users = userDao.findUserByName("%王%");
List<User> users = userDao.findUserByName("王");
for (User user : users) {
System.out.println(user);
}
}
@Test
public void testFindTotal(){
int total = userDao.findTotalUser();
System.out.println(total);
}
}
如果字段配置和数据库不一致解决方法
// 在mybatis中针对CRUD一共有四个注解:@SelectT @Insert @Update @Delete
public interface IUserDao {
// 查询所有用户
@Select("select * from user")
@Results(id = "userMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "address",property = "address"),
@Result(column = "sex",property = "sex"),
@Result(column = "birthday",property = "birthday"),
})
List<User> findAll();
// 根据条件查询
@Select("select * from user where id=#{id}")
// @ResultMap(value = {"userMap"}) //标准写法
@ResultMap("userMap")
User findById(Integer userId);
// 根据用户名称模糊查询
@ResultMap("userMap")
@Select("select * from user where username like #{username}")
List<User> findUserByName(String username);
}
多表
一对一配置
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
// 多对一对应关系
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}
public interface IAccountDao {
// 查询所有账户,并且获取每个账户所属的用户信息
@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.itcase.dao.IUserDao.findById",fetchType= FetchType.EAGER))
})
List<Account> findAll();
}
public class AccountTest {
private SqlSessionFactory factory;
private SqlSession session;
private InputStream in;
private IAccountDao accountDao;
@Before
public void init() throws Exception {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
accountDao = session.getMapper(IAccountDao.class);
}
@After
public void dastroy() throws Exception {
session.commit();
session.close();
in.close();
}
@Test
public void testFindAll() {
List<Account> accounts = accountDao.findAll();
for (Account account : accounts) {
System.out.println(account);
System.out.println(account.getUser());
}
}
}
一对多
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
//一对多关系映射
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
// 多对一对应关系
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}
public interface IUserDao {
// 查询所有用户
@Select("select * from user")
@Results(id = "userMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "address",property = "address"),
@Result(column = "sex",property = "sex"),
@Result(column = "birthday",property = "birthday"),
@Result(property = "accounts",column = "id",many = @Many(select="com.itcase.dao.IAccountDao.findAccountByUid",fetchType= FetchType.LAZY))
})
List<User> findAll();
// 根据条件查询
@Select("select * from user where id=#{id}")
@ResultMap(value = {"userMap"}) //标准写法
User findById(Integer userId);
// 根据用户名称模糊查询
@ResultMap("userMap")
@Select("select * from user where username like #{username}")
List<User> findUserByName(String username);
}
public interface IAccountDao {
// 查询所有账户,并且获取每个账户所属的用户信息
@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.itcase.dao.IUserDao.findById",fetchType= FetchType.EAGER))
})
List<Account> findAll();
// 根据用户ID查询账户信息
@Select("select * from account where uid = #{userid}")
List<Account> findAccountByUid(Integer userId);
}
public class AccountTest {
private SqlSessionFactory factory;
private SqlSession session;
private InputStream in;
private IAccountDao accountDao;
@Before
public void init() throws Exception {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
accountDao = session.getMapper(IAccountDao.class);
}
@After
public void dastroy() throws Exception {
session.commit();
session.close();
in.close();
}
@Test
public void testFindAll() {
List<Account> accounts = accountDao.findAll();
for (Account account : accounts) {
System.out.println(account);
System.out.println(account.getUser());
}
}
}
public class AnnotationCRUDTest {
private SqlSessionFactory factory;
private SqlSession session;
private InputStream in;
private IUserDao userDao;
@Before
public void init() throws Exception {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(IUserDao.class);
}
@After
public void dastroy() throws Exception {
session.commit();
session.close();
in.close();
}
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
System.out.println(user.getAccounts());
}
}
}
二级缓存
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 引入外部配置文件 -->
<properties resource="jdbcConfig.properties"></properties>
<!-- 配置开启二级缓存 -->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 配置别名 -->
<typeAliases>
<package name="com.itcase.domain"></package>
</typeAliases>
<!-- 配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 指定带有注解的dao接口所在位置 -->
<mappers>
<package name="com.itcase.dao"></package>
<!-- <mapper class="com.itcase.dao.IUserDao"></mapper>-->
</mappers>
</configuration>
@CacheNamespace(blocking = true)
public interface IUserDao {
// 查询所有用户
@Select("select * from user")
@Results(id = "userMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "address",property = "address"),
@Result(column = "sex",property = "sex"),
@Result(column = "birthday",property = "birthday"),
@Result(property = "accounts",column = "id",many = @Many(select="com.itcase.dao.IAccountDao.findAccountByUid",fetchType= FetchType.LAZY))
})
List<User> findAll();
// 根据条件查询
@Select("select * from user where id=#{id}")
@ResultMap(value = {"userMap"}) //标准写法
User findById(Integer userId);
// 根据用户名称模糊查询
@ResultMap("userMap")
@Select("select * from user where username like #{username}")
List<User> findUserByName(String username);
}
public class SecondLevelCatchTest {
private SqlSessionFactory factory;
private InputStream in;
@Before
public void init() throws Exception {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
}
@After
public void dastroy() throws Exception {
in.close();
}
@Test
public void testFindOne(){
SqlSession session = session = factory.openSession();
IUserDao userDao = session.getMapper(IUserDao.class);
User user = userDao.findById(48);
System.out.println(user);
session.close(); // 释放一级缓存
SqlSession session1 = factory.openSession(); // 再次打开session
IUserDao userDao1 = session1.getMapper(IUserDao.class);
User user2 = userDao1.findById(48);
System.out.println(user2);
session.close(); // 释放二级缓存
System.out.println(user == user2);
}
}