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

(一)网站基金来源:

2019年本站VIP服务,收徒公告:>>>>>>


(二)入群须知:

凡是加入我群者,皆要严守群规,每周日是群规反思日。群规的要义有两点∶

(1)坚持系统化的学习方式,由量变到质变。仅仅解决工作中的问题,并不叫系统化的学习。

(2)坚持以价值为导向的学习方式,扔掉低价值知识[配置、调参、安装],聚焦高价值知识[结构、算法、优化],推动量变到质变的进程。

添加新评论