项目准备
导入前面项目的pom文件,实体类
一对一的关联映射
实体类:
public class Account implements Serializable {
在这里插入代码片
```private Integer id;
private Integer uid;
private Double money;
private User user;
//省略了getter和setter,省略了toString
}
查询账号的同时查询出账户绑定的用户信息,所以需要在账户实体类中定义用户的信息,一对一的映射所以是简单的对象,而不是集合对象。
接口实现类:
public interface AccountDao {
/**
* 查找所有
* @return
*/
@Select("select * from account")
@Results(id="AccountMap", value={
@Result(id=true,property = "id",column = "id"),
@Result(property = "uid",column = "uid"),
@Result(property = "money",column = "money"),
/*
uid是关联两个表的关联属性,account的uid和user的id属性对应,所有column选择uid属性,property属性是指要关联的表
one表示的是一对一关联,对应的还有多对多,通过@one注解实现查询语句,直接找到需要实现的方法并用全限定类名写出。
*/
@Result(property = "user",column = "uid",one = @One(select = "com.cz.dao.UserDao.findById"))
})
List<Account> findAll();
}
/**
* 查找一个
* @param id
*/
@Select("select * from user where id=#{id}")
User findById(Integer id);
首先,查询的是账户信息,所以账户查询是主体,所以所有的信息在账户查询上,@Select注解首先查出所有的account,对应的是映射文件中的sql语句,@Results注解对应的是ResultMap标签,id是这个map的唯一标识,value值是对关联属性的映射,@Result注解代替了id标签和result标签,第一个值的id=true表示是主键,property表示的是实体类的属性名,column表示的是数据库表的列名。
最后一个result注解中uid是关联两个表的关联属性,account的uid和user的id属性对应,所有column选择uid属性,property属性是指要关联的表。
@one注解代替了association标签,在注解中用来指定子查询返回的单一对象。select用来指定多表查询的sqlmapper,值用方法的全限定类名。
使用格式:@Result(column=" “,property=”",one=@One(select=""))
同时需要在user的接口中定义一个根据id查询的方法,这个就是用来和前面的一对一查询做匹配的。
测试方法:
/**
* 一个账户只能是一个用户所有,所以这是一对一的关联
*/
@Test
public void TestFindAll(){
List<Account> accounts = accountDao.findAll();
for(Account account:accounts){
System.out.println("----------每个账户对应的用户信息-----------");
System.out.println(account);
System.out.println(account.getUser());
}
}
测试结果和前面的关联查询一样。
一对多的关联查询
public class User {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
List<Account> accounts;
//省略了getter和setter,省略了toString
}
一对多中会映射出多个查询结果,所以需要用集合对象来接收,这里采用List集合。
接口实现类:
/**
* 查找所有对象
* @return
*/
@Select("select * from user")
@Results(id="UserMap",value = {
@Result(id = true,property = "id",column = "id"),
@Result(property = "sex" ,column = "sex"),
@Result(property = "birthday" ,column = "birthday"),
@Result(property = "username" ,column = "username"),
@Result(property = "address" ,column = "address"),
@Result(property = "accounts",column = "id",many = @Many(select = "com.cz.dao.AccountDao.findAccountByUid"))
})
List<User> findAll();
@Select("select * from account where uid=#{UserId}")
List<Account> findAccountByUid(Integer UserId);
这里和一对一 查询相似,不同的是一对多采用many注解,property元素表示的是实体类的属性名,column表示的是需要关联的属性。
@Many:相当于collection标签的配置,select 属性:代表将要执行的 sql 语句
使用格式:@Result(property="",column="",many=@Many(select=""))
测试类:
/**
* 一个用户可以有多个账户,这里是一对多映射
*/
@Test
public void TestFindAll(){
List<User> users = userDao.findAll();
for (User user :users){
System.out.println("----------每个用户对应的账户信息-------------");
System.out.println(user);
System.out.println(user.getAccounts());
}
}
查询结果和前面的非注解结果一样。