Mybatis基于注解实现多表查询
对应的四种数据库表关系中存在四种关系:一对多,多对应,一对一,多对多。在前文中已经实现了xml配置方式实现表关系的查询,本文记录一下Mybatis怎么通过注解实现多表的查询,算是一个知识的补充。
同样的先介绍一下Demo的情况:存在两个实体类用户类和账户类,用户类可能存在多个账户,即一对多的表关系。每个账户只能属于一个用户,即一对一或者多对一关系。我们最后实现两个方法,第一个实现查询所有用户信息并同时查询出每个用户的账户信息,第二个实现查询所有的账户信息并且同时查询出其所属的用户信息。
1.项目结构
2.领域类
public class Account implements Serializable{ private Integer id; private Integer uid; private double money; private User user; //加入所属用户的属性 省略get 和set 方法............................. }public class User implements Serializable{
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
private List<Account> accounts;
省略get 和set 方法.............................
}
在User中因为一个用户有多个账户所以添加Account的列表,在Account中因为一个账户只能属于一个User,所以添加User的对象。
3.Dao层

1 public interface AccountDao { 2 /** 3 *查询所有账户并同时查询出所属账户信息 4 */ 5 @Select("select * from account") 6 @Results(id = "accountMap",value = { 7 @Result(id = true,property = "id",column = "id"), 8 @Result(property = "uid",column = "uid"), 9 @Result(property = "money",column = "money"), 10 //配置用户查询的方式 column代表的传入的字段,一对一查询用one select 代表使用的方法的全限定名, fetchType表示查询的方式为立即加载还是懒加载 11 @Result(property = "user",column = "uid",one = @One(select = "com.example.dao.UserDao.findById",fetchType = FetchType.EAGER)) 12 }) 13 List<Account> findAll(); 14 15 /** 16 * 根据用户ID查询所有账户 17 * @param id 18 * @return 19 */ 20 @Select("select * from account where uid = #{id}") 21 List<Account> findAccountByUid(Integer id); 22 } 23 24 25 26 public interface UserDao { 27 /** 28 * 查找所有用户 29 * @return 30 */ 31 @Select("select * from User") 32 @Results(id = "userMap",value = {@Result(id = true,column = "id",property = "userId"), 33 @Result(column = "username",property = "userName"), 34 @Result(column = "birthday",property = "userBirthday"), 35 @Result(column = "sex",property = "userSex"), 36 @Result(column = "address",property = "userAddress"), 37 @Result(column = "id",property = "accounts",many = @Many(select = "com.example.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY)) 38 }) 39 List<User> findAll(); 40 41 /** 42 * 保存用户 43 * @param user 44 */ 45 @Insert("insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})") 46 void saveUser(User user); 47 48 /** 49 * 更新用户 50 * @param user 51 */ 52 @Update("update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}") 53 void updateUser(User user); 54 55 /** 56 * 删除用户 57 * @param id 58 */ 59 @Delete("delete from user where id=#{id}") 60 void deleteUser(Integer id); 61 62 /** 63 * 查询用户根据ID 64 * @param id 65 * @return 66 */ 67 @Select("select * from user where id=#{id}") 68 @ResultMap(value = {"userMap"}) 69 User findById(Integer id); 70 71 /** 72 * 根据用户名称查询用户 73 * @param name 74 * @return 75 */ 76 // @Select("select * from user where username like #{name}") 77 @Select("select * from user where username like '%${value}%'") 78 List<User> findByUserName(String name); 79 80 /** 81 * 查询用户数量 82 * @return 83 */ 84 @Select("select count(*) from user") 85 int findTotalUser();
在findAll()方法中配置@Results的返回值的注解,在@Results注解中使用@Result配置根据用户和账户的关系而添加的属性,User中的属性List<Account>一个用户有多个账户的关系的映射配置:@Result(column = "id",property = "accounts",many = @Many(select = "com.example.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY)),使用@Many来向Mybatis表明其一对多的关系,@Many中的select属性对应的AccountDao中的findAccountByUid方法的全限定名,fetchType代表使用立即加载或者延迟加载,因为这里为一对多根据前面的讲解,懒加载的使用方式介绍一对多关系一般使用延迟加载,所以这里配置为LAZY方式。在Account中存在多对一或者一对一关系,所以配置返回值属性时使用:@Result(property = "user",column = "uid",one = @One(select = "com.example.dao.UserDao.findById",fetchType = FetchType.EAGER)),property代表领域类中声明的属性,column代表传入后面select语句中的参数,因为这里为一对一或者说为多对一,所以使用@One注解来描述其关系,EAGER表示使用立即加载的方式,select代表查询本条数据时所用的方法的全限定名,fetchType代表使用立即加载还是延迟加载。
4.Demo中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> <settings> <!--<!–开启全局的懒加载–>--> <!--<setting name="lazyLoadingEnabled" value="true"/>--> <!--<!–关闭立即加载,其实不用配置,默认为false–>--> <!--<setting name="aggressiveLazyLoading" value="false"/>--> <!--开启Mybatis的sql执行相关信息打印--> <setting name="logImpl" value="STDOUT_LOGGING" /> <!--<setting name="cacheEnabled" value="true"/>--> </settings> <typeAliases> <typeAlias type="com.example.domain.User" alias="user"/> <package name="com.example.domain"/> </typeAliases> <environments default="test"> <environment id="test"> <!--配置事务--> <transactionManager type="jdbc"></transactionManager> <!--配置连接池--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test1"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <package name="com.example.dao"/> </mappers> </configuration>
主要是记得开启mybatis中sql执行情况的打印,方便我们查看执行情况。
5.测试
(1)测试查询用户同时查询出其账户的信息
测试代码:
public class UserTest {
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> InputStream in;
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> SqlSessionFactory sqlSessionFactory;
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> SqlSession sqlSession;
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> UserDao userDao;
@Before
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> init()<span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> Exception{
in </span>= Resources.getResourceAsStream("SqlMapConfig.xml"<span style="color: rgba(0, 0, 0, 1)">);
sqlSessionFactory </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> SqlSessionFactoryBuilder().build(in);
sqlSession </span>=<span style="color: rgba(0, 0, 0, 1)"> sqlSessionFactory.openSession();
userDao </span>= sqlSession.getMapper(UserDao.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);
}
@After
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> destory()<span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> Exception{
sqlSession.commit();
sqlSession.close();
in.close();
}
@Test
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> testFindAll(){
List</span><User> userList =<span style="color: rgba(0, 0, 0, 1)"> userDao.findAll();
</span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (User user: userList){
System.out.println(</span>"每个用户信息"<span style="color: rgba(0, 0, 0, 1)">);
System.out.println(user);
System.out.println(user.getAccounts());
}
}</span></pre>
测试结果:
(2)查询所有账户信息同时查询出其所属的用户信息
测试代码:
public class AccountTest {
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> InputStream in;
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> SqlSessionFactory sqlSessionFactory;
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> SqlSession sqlSession;
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> AccountDao accountDao;
@Before
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> init()<span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> Exception{
in </span>= Resources.getResourceAsStream("SqlMapConfig.xml"<span style="color: rgba(0, 0, 0, 1)">);
sqlSessionFactory </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> SqlSessionFactoryBuilder().build(in);
sqlSession </span>=<span style="color: rgba(0, 0, 0, 1)"> sqlSessionFactory.openSession();
accountDao </span>= sqlSession.getMapper(AccountDao.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);
}
@After
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> destory()<span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> Exception{
sqlSession.commit();
sqlSession.close();
in.close();
}
@Test
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> testFindAll(){
List</span><Account> accountList =<span style="color: rgba(0, 0, 0, 1)"> accountDao.findAll();
</span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (Account account: accountList){
System.out.println(</span>"查询的每个账户"<span style="color: rgba(0, 0, 0, 1)">);
System.out.println(account);
System.out.println(account.getUser());
}
}
}
测试结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)