1、映射接口
- public interface CardMapper
- {
- @Select("SELECT * FROM tb_card WHERE ID = #{id} ")
- Card selectCardById(Integer id);
- }
- public interface PersonMapper
- {
-
- @Select("SELECT * FROM tb_person WHERE ID = #{id}")
- @Results(
- { @Result(id = true, column = "id", property = "id"), @Result(column = "name", property = "name"),
- @Result(column = "sex", property = "sex"), @Result(column = "age", property = "age"),
- @Result(column = "card_id", property = "card", one = @One(select = "cn.mybatis.mydemo4.mapper.CardMapper.selectCardById", fetchType = FetchType.EAGER)) })
-
- Person selectPersonById(Integer id);
-
- }
2、引入映射接口
- <mappers>
- <mapper class="cn.mybatis.mydemo4.mapper.PersonMapper" />
- <mapper class="cn.mybatis.mydemo4.mapper.CardMapper" />
- </mappers>
3、工具类
- public class MySqlSessionFactory
- {
-
- private static SqlSessionFactory sqlSessionFactory = null;
-
-
- static
- {
- try
- {
-
- InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
- sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
-
-
- public static SqlSession getSqlSession()
- {
- return sqlSessionFactory.openSession();
- }
-
-
- public static SqlSessionFactory getSqlSessionFactory()
- {
- return sqlSessionFactory;
- }
-
- }
-
4、测试代码
- public class App
- {
- public static void main(String[] args) throws Exception
- {
-
- SqlSession session = MySqlSessionFactory.getSqlSession();
-
- PersonMapper pm = session.getMapper(PersonMapper.class);
-
- Person p = pm.selectPersonById(1);
-
- System.out.println(p);
-
- System.out.println(p.getCard());
-
- session.commit();
-
- session.close();
- }
- }
你这个案例是自己写的吗?