@Data
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
}
SELECT
account.*,
user.username,
user.address
FROM
account,
`user`
WHERE account.uid = user.id;
在 MySQL 中测试的查询结果如下:
@Data
public class AccountUser extends Account implements Serializable {
private String username;
private String address;
}
public interface IAccountDao {
/**
* 查询所有账户,同时获取账户的所属用户名称以及它的地址信息
* @return
*/
List findAll();
}
/**
* @ClassName: AccountTest
* @Author: linxin
* @Date: 2021/6/13 19:12
* @Company: http://www.oesoft.cn
* @Description: 一对多账户的操作
*/
public class AccountTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
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);
}
@After//在测试方法执行完成之后执行
public void destroy() throws Exception {
session.commit();
//7.释放资源
session.close();
in.close();
}
@Test
public void testFindAll() {
//6.执行操作
List accountusers = accountDao.findAll();
for (AccountUser au : accountusers) {
System.out.println(au);
}
}
}
在 Account 类中加入 User 类的对象作为 Account 类的一个属性。
private User user;
/**
* 查询所有账户,同时获取账户的所属用户名称以及它的地址信息
* @return
*/
List findAll();
@Test
public void testFindAll() {
List accounts = accountDao.findAll();
for(Account au : accounts) {
System.out.println(au);
System.out.println(au.getUser());
} }
SELECT
u.*, acc.id id,
acc.uid,
acc.money
FROM
`user` u
LEFT JOIN account acc ON u.id = acc.uid;
private List accounts;
/**
* 查询所有用户,同时获取出每个用户下的所有账户信息
* @return
*/
List findAllWithAccounts();
@Test
public void testFindAllWithAccounts() {
//6.执行操作
List users = userDao.findAllWithAccounts();
for(User user : users) {
System.out.println("-------每个用户的内容---------");
System.out.println(user);
System.out.println(user.getAccounts());
} }