本文主要是介绍MyBatis注解之多对一,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、CategoryMapper(一方)
public interface CategoryMapper {@Select(" select * from category_ where id = #{id}")public Category get(int id);
}
2、ProductMapper(多方)
public interface ProductMapper {@Select(" select * from product_ ")@Results({ @Result(property="category",column="cid",one=@One(select="com.how2java.mapper.CategoryMapper.get")) })public List<Product> list();
}
3、mybatis-config.xml
<mappers><mapper class="com.how2java.mapper.CategoryMapper"/> <mapper class="com.how2java.mapper.ProductMapper"/> </mappers>
4、Test类
public class TestMybatis {public static void main(String[] args) throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession session = sqlSessionFactory.openSession();ProductMapper mapper = session.getMapper(ProductMapper.class);List<Product> ps= mapper.list();for (Product p : ps) {System.out.println(p + "\t对应的分类是:\t" + p.getCategory().getName());}session.commit();session.close();}
}
运行结果:
这篇关于MyBatis注解之多对一的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!