Flutter开发App的未来及其在各行业的应用潜力分析
971
2023-03-23
Mybatis关联查询之一对多和多对一XML配置详解
平时在开发过程中dao、bean和XML文件都是自动生成的,很少写XML的配置关系,今天记录一下mybatis的关联查询中的多对一和一对多的情况。
首先是有两张表(学生表Student和老师Teacher表,注:这里只是为了演示一对多和多对一的情况,请不要杠),为了更易懂,这里只设置了最简单的几个必要字段。表结构如下图
Student表:
Teacher表:
创建实体bean
Teacher.java:
import java.util.List;
public class Teacher {
private Integer id;
private String name;
private String className;
private List
// get、set方法省略
}
Sfudent.java
public class Student {
private Integer id;
private String name;
private Integer teacherId;
private String className;
private Teacher teacher;
// get、set方法省略
}
下面重点来了:配置Mapper.xml文件:
SELECT
t.id,
t.NAME,
t.class_Name,
s.id AS sid,
s. NAME AS sname,
s.class_name as className
FROM
teacher t
LEFT JOIN student shttp:// ON t.id = s.teacher_id
测试类:
package com.tz.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.tz.mybatis.bean.Student;
import com.tz.mybatis.bean.Teacher;
public class TeacherTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void getTeachers() {
SqlSession session = sqlSessionFactory.openSession();
List
System.out.println(list);
}
}
下面给出第二种写法:
SELECT
t.id,
t.NAME,
t.class_name
FROM
teacher t
select
s.id,
s. NAME,
s.class_name as className
from student s
where teacher_id = #{id}
测试类:
@Test
public void getTeachers2() {
SqlSession session = sqlSessionFactory.openSession();
List
System.out.println(list);
}
查询学生信息(多对一):
首先还是配置文件:
SELECT
s.id,
s.name,
s.class_name,
s.teacher_id
FROM
student s
SELECT
t.id,
t.name,
t.class_name as className
FROM teacher t
where id = #{teacher_id}
测试类:
@Test
public void getStudents() {
SqlSession session = sqlSessionFactory.openSession();
List
System.out.println(list);
}
最后:当然如果不想配置这么麻烦的信息,可以直接写一个关联查询的SQL语句,返回结果直接由Map接受即可。不过这样就不太符合面向对象的理念了。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~