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层
1public 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 = "ample.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
26public 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 = "ample.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})")
46void 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}")
53void updateUser(User user);
54
55/**heap和stack区别
56    * 删除⽤户
57    * @param id
58*/
59    @Delete("delete from user where id=#{id}")
60void  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")
85int findTotalUser();
span的用法View Code
  在findAll()⽅法中配置@Results的返回值的注解,在@Results注解中使⽤@Result配置根据⽤户和账户的关系⽽添加的属性,User中的属性List<Account>⼀个⽤户有多个账户的关系的映射配置:@Result(column = "id",property = "accounts",many = @Many(select =
"ample.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY)),使⽤@Many来向Mybatis表明其⼀对多的关系,@Many中的select属性对应的AccountDao中的findAccountByUid⽅法的全限定名,fetchType代表使⽤⽴即加载或者延迟加载,因为这⾥为⼀对多根据前⾯的讲解,懒加载的使⽤⽅式介绍⼀对多关系⼀般使⽤延迟加载,所以这⾥配置为LAZY⽅式。在Account中存在多对⼀或者⼀对⼀关系,所以配置返回值属性时使⽤:@Result(property = "user",column = "uid",one = @One(select = "ample.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 "-////DTD Config 3.0//EN"linux操作系统镜像下载
"/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--<!&ndash;开启全局的懒加载–>-->
<!--<setting name="lazyLoadingEnabled" value="true"/>-->
1到10随机数生成器不重复<!--<!&ndash;关闭⽴即加载,其实不⽤配置,默认为false–>-->
<!--<setting name="aggressiveLazyLoading" value="false"/>-->
<!--开启Mybatis的sql执⾏相关信息打印-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--<setting name="cacheEnabled" value="true"/>-->
</settings>
<typeAliases>
<typeAlias type="ample.domain.User" alias="user"/>
<package name="ample.domain"/>
</typeAliases>
<environments default="test">
<environment id="test">
<!--配置事务-->
<transactionManager type="jdbc"></transactionManager>
<!--配置连接池-->
<dataSource type="POOLED">
<property name="driver" value="sql.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="ample.dao"/>
</mappers>
</configuration>
  主要是记得开启mybatis中sql执⾏情况的打印,⽅便我们查看执⾏情况。
  5.测试
  (1)测试查询⽤户同时查询出其账户的信息
   测试代码:
public class UserTest {
private InputStream in;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
private UserDao userDao;
@Before
public void init()throws Exception{
in = ResourceAsStream("l");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
sqlSession = sqlSessionFactory.openSession();
userDao = Mapper(UserDao.class);
}
@After
public void destory()throws Exception{
sqlSessionmit();
sqlSession.close();
in.close();
}
@Test
public void testFindAll(){
List<User> userList = userDao.findAll();
for (User user: userList){
System.out.println("每个⽤户信息");
System.out.println(user);
System.out.Accounts());
}
}
  测试结果:
(2)查询所有账户信息同时查询出其所属的⽤户信息  测试代码:
public class AccountTest {
private InputStream in;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
private AccountDao accountDao;
@Before
public void init()throws Exception{
in = ResourceAsStream("l");        sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);        sqlSession = sqlSessionFactory.openSession();
accountDao = Mapper(AccountDao.class);
}
@After
public void destory()throws Exception{
sqlSessionmit();
source代码
sqlSession.close();
in.close();
}
@Test
public void testFindAll(){
List<Account> accountList = accountDao.findAll();
for (Account account: accountList){
System.out.println("查询的每个账户");
mysql语句多表查询System.out.println(account);
System.out.User());
}
}
}
测试结果:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。