MyBatis的一对一关联关系(注解形式)

415人浏览 / 0人评论
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、引入映射接口

        
        
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();
    }
}

全部评论

晴天下起了小雨
2017-10-01 18:00
很喜欢,果断关注了
wjmyly7336064
2017-10-01 18:00
相当实用,赞美了
橘大佬
2017-10-01 18:00
就是有些细节再到位点就好了…