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;

    // 初始化创建SqlSessionFactory对象
    static
    {
        try
        {
            // 读取mybatis-config.xml文件
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    // 获取SqlSession对象的静态方法
    public static SqlSession getSqlSession()
    {
        return sqlSessionFactory.openSession();
    }

    // 获取SqlSessionFactory的静态方法
    public static SqlSessionFactory getSqlSessionFactory()
    {
        return sqlSessionFactory;
    }

}

4、测试代码

public class App
{
    public static void main(String[] args) throws Exception
    {
        // 获取Session实例
        SqlSession session = MySqlSessionFactory.getSqlSession();
        // 获取PersonMapper实例
        PersonMapper pm = session.getMapper(PersonMapper.class);
        // 根据id查询Person对象,同时需要获得关联的Card对象
        Person p = pm.selectPersonById(1);
        // 查看查询到的Person对象
        System.out.println(p);
        // 查看查询到的关联的Card对象
        System.out.println(p.getCard());
        // 提交事务
        session.commit();
        // 关闭Session
        session.close();
    }
}

标签: none

仅有一条评论

  1. 你这个案例是自己写的吗? 你这个案例是自己写的吗?

    你这个案例是自己写的吗?

添加新评论