MyBatis one to one 對映
阿新 • • 發佈:2018-12-09
Card類
public class Card {
private int id;
private String cardNo;
private String address;
private Person person;
....
Person類
public class Person {
private int id;
private String name;
private Card card;
......
PersonDao類
public interface PersonDao {
List<Person> getPersons() throws Exception;
Person getPersonById(int id) throws Exception;
}
CardDao類
public interface CardDao {
List<Card> getCards() throws Exception;
Card getCardById(int id) throws Exception;
}
CardDao.xml 對映檔案
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hsj.dao.CardDao">
<select id="getCards" resultMap="resultMap_Card">
select * from t_card c inner join t_person p on c.person_id=p.p_id
</select>
<resultMap type="card" id="resultMap_Card">
<id column="c_id" property="id" />
<result column="c_cardno" property="cardNo"/>
<result column="c_address" property="address"/>
<association property="person" column="person_id" javaType="person">
<id column="p_id" property="id"/>
<result column="p_name" property="name"/>
</association>
</resultMap>
<select id="getCardById" parameterType="int" resultMap="resultMap_Card">
select * from t_card c inner join t_person p on c.person_id=p.p_id and c_id=#{id}
</select>
</mapper>
PersonDao.xml對映檔案
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hsj.dao.PersonDao">
<select id="getPersons" resultMap="resultMap_Person">
select * from t_person p inner join t_card c on p.p_id=c.person_id
</select>
<resultMap type="person" id="resultMap_Person">
<id column="p_id" property="id"/>
<result column="p_name" property="name"/>
<association property="card" column="person_id" javaType="card">
<id column="c_id" property="id"/>
<result column="c_cardno" property="cardNo"/>
<result column="c_address" property="address"/>
</association>
</resultMap>
<select id="getPersonById" parameterType="int" resultMap="resultMap_Person">
select * from t_person p inner join t_card c on p.p_id=c.person_id and p_id=#{id}
</select>
</mapper>
其中的一個測試類 public class PersonDaoTest {
private PersonDao personDao;
@Before
public void setUp() throws Exception {
SqlSession sqlSession=MyBatisUtils.getSqlSession();
this.personDao=sqlSession.getMapper(PersonDao.class);
}
@Test
public void testGetPersons() {
try {
List<Person> persons=this.personDao.getPersons();
for(Person p:persons){
System.out.println(p+"==>"+p.getCard());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testGetPerson() {
try {
int id=1;
Person person=this.personDao.getPersonById(id);
System.out.println(person+"==>"+person.getCard());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}