注解开发中一对一关系的处理方式


package com.hope.dao;

import com.hope.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;

/**
* @author newcityman
* @date 2019/11/17 - 19:50
*/
public interface IAccountDao {
/**
* 查询所有账户信息
*/
@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.hope.dao.IUserDao.findOne",
fetchType = FetchType.EAGER
))
})
public List<Account> findAll();
}

package com.hope.test;

import com.hope.dao.IAccountDao;
import com.hope.domain.Account;
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;

/**
* @author newcityman
* @date 2019/11/17 - 20:02
*/
public class AccountTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private IAccountDao accountDao;

@Before
public void init() throws Exception {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
sqlSession = factory.openSession();
accountDao = sqlSession.getMapper(IAccountDao.class);
}
@After
public void destroy()throws Exception{
sqlSession.close();
in.close();
}

@Test
public void testFindAll() {
List<Account> accounts = accountDao.findAll();
for(Account account:accounts){
System.out.println(account);
System.out.println(account.getUser());
}
}
}
 
posted on 2019-11-17 20:18  小猪_佩奇  阅读(304)  评论(0编辑  收藏  举报