1.复杂关系映射的注解说明
@Results 注解 代替的是标签<resultMap> 该注解中可以使用单个@Result 注解,也可以使用@Result 集合 @Results({@Result(), @Result() })或@Results(@Result()) @Resutl 注解 代替了 <id>标签和<result>标签 @Result 中 属性介绍: id 是否是主键字段 column 数据库的列名 property 需要装配的属性名 one 需要使用的@One 注解(@Result(one=@One)())) many 需要使用的@Many 注解(@Result(many=@many)())) @One 注解(一对一) 代替了<assocation>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。 @One 注解属性介绍: select 指定用来多表查询的 sqlmapper fetchType 会覆盖全局的配置参数 lazyLoadingEnabled。。 使用格式: @Result(column=" ",property="",one=@One(select="")) @Many 注解(多对一) 代替了<Collection>标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。 注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType (一般为 ArrayList)但是注解中可以不定义; 使用格式: @Result(property="",column="",many=@Many(select=""))
2.使用注解实现一对一复杂关系映射及延迟加载
2.1.User类
package com.domain; import java.io.Serializable; import java.util.Date; public class User implements Serializable{ private Integer userId; private String userName; private Date userBirthday; private String userSex; private String userAddress; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } @Override public String toString() { return "User{" + "userId=" + userId + ", userName='" + userName + '\'' + ", userBirthday=" + userBirthday + ", userSex='" + userSex + '\'' + ", userAddress='" + userAddress + '\'' + '}'; } }
2.2.Account类
package com.domain; import java.io.Serializable; 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 + '}'; } }
3.添加账户的持久层接口并使用注解配置
package com.dao; import com.domain.User; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.ResultMap; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import java.util.List; //用户的持久层接口 public interface IUserDao { @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(); /** * 根据 id 查询一个用户 * @param userId * @return */ @Select("select * from user where id = #{uid} ") @ResultMap("userMap") User findById(Integer userId); } 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 IAccountDao { /** * 查询所有账户,采用延迟加载的方式查询账户的所属用户 * @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(column="uid", property="user", one=@One(select="com.dao.IUserDao.findById", fetchType= FetchType.LAZY) ) }) List<Account> findAll(); }
4.全局配置文件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"> <configuration> <!-- 引入外部配置文件--> <properties resource="jdbcConfig.properties"></properties> <!--配置开启二级缓存--> <settings> <setting name="cacheEnabled" value="true"/> </settings> <!--配置别名--> <typeAliases> <package name="com.domain"></package> </typeAliases> <!-- 配置环境--> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </dataSource> </environment> </environments> <!-- 指定带有注解的dao接口所在位置 --> <mappers> <package name="com.dao"></package> </mappers> </configuration>
5.测试类
package com.test; import com.dao.IAccountDao; import com.dao.IUserDao; import com.domain.Account; import com.domain.AccountUser; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.List; //测试mybatis的crud方法 public class MybatisTest { private InputStream in ; private SqlSessionFactory factory; private SqlSession session; private IUserDao userDao; private AccountUser accountUser; private IAccountDao accountDao; // 测试查询所有方法 @Before //在测试之前执行 public void init()throws Exception { //1.读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建构建者对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //3.创建 SqlSession 工厂对象 factory = builder.build(in); //4.创建 SqlSession 对象 session = factory.openSession(); //5.创建 Dao 的代理对象 accountDao = session.getMapper(IAccountDao.class); // accountUser = session.getMapper(AccountUser.class); } @Test public void testFirstLevelCache(){ List<Account> accounts = accountDao.findAll(); for(Account account : accounts){ System.out.println("----每个账户的信息-----"); System.out.println(account); System.out.println(account.getUser()); } } @After//在测试方法执行完成之后执行 public void destroy() throws Exception{ //提交事务 session.commit(); //7.释放资源 session.close(); in.close(); } } ## ```6.结果 ![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/20210204210629450.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hlMTIzNDU1NQ==,size_16,color_FFFFFF,t_70)