实体关系问题
- 1:1
多表查询
package com.zakl.pojo;
import java.io.Serializable;
//返回的查询类
public class Userwithdetailpojo extends User2pojo implements Serializable {
private Userdetailpojo userdetailpojo;
//省略get set toString
}
使用泛型方法进行测试
public static void queryautocommit(String methodname,Object[] objs) throws InvocationTargetException, IllegalAccessException {
SqlSession sqlSession = MybatisUtil.getSession();
User2Mapper user2Mapper = sqlSession.getMapper(User2Mapper.class);
Method[] methods=user2Mapper.getClass().getMethods();
Method method=null;
for (int i=0;i userwithdetailpojos= (List) method.invoke(user2Mapper,objs);
System.out.println(userwithdetailpojos);
sqlSession.close();
}
@Test
public void testdemo() throws InvocationTargetException, IllegalAccessException {
Object[] objects=new Object[]{1};
queryautocommit("querybyid",objects);
}
使用分步查詢
UserdetailMapper查詢文件
public interface User2Mapper {
List querybyid(@Param("id") Integer id);
List querybystepid(@Param("id") Integer id);
}
public interface UserdetailMapper {
List querybyUseridbystep(@Param("userid") Integer userid);
}
@Test
public void demo11() {
SqlSession sqlSession = MybatisUtil.getSession();
User2Mapper user2Mapper=sqlSession.getMapper(User2Mapper.class);
List userwithdetailpojos = user2Mapper.querybystepid(1);
System.out.println(userwithdetailpojos);
sqlSession.commit();
sqlSession.close();
}
注意每次新增Mapper.xml時都應該在mybatis.cfg.xml中進行配置
- 1:n
多表联合查询
三表结构
[图片上传失败...(image-b43e37-1545553459517)]
三个pojo类
public class UserwithBlog extends User2pojo implements Serializable {
private List blogs;
}
public class Blog {
private Integer id;
private User2pojo user2pojo;
private String title;
private String content;
private List comments;
}
public class Comment {
private Integer id;
private String comment;
private Blog blog;
}
//接口方法
@interface
UserwithBlog querblogbyid(@Param("userid")Integer userid);
mapper.xml配置