Mybatis中联合查询

实体类有Employee和Project,这次要通过联合查询,通过雇员的id查找雇员所做的项目,对应的数据库的字段为:
这里写图片描述
新建一个实体类project,属性并没和数据库对应:

package micro.model;
/**
@author:micro_hz
2015年8月20日
 */
public class Project {
    int id;
    //这里属性有Employee类型
    Employee employee;
    String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Employee getEmployee() {
        return employee;
    }
    public void setEmployee(Employee employee) {
        this.employee = employee;
    }
}

Employee:

package micro.model;
/**
@author:micro_hz
2015年8月19日
 */
public class Employee {
    int id;
    String name;
    int age;
    String address;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }

}

Configuration.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="User" type="micro.model.User" />
        <typeAlias alias="Student" type="micro.model.Student" />
        <typeAlias alias="Employee" type="micro.model.Employee" />
        <typeAlias alias="Article" type="micro.model.Article"/>
        <typeAlias alias="Project" type="micro.model.Project"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/micro" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="micro/mapper/User.xml" />
        <mapper resource="micro/mapper/Student.xml" />
        <mapper resource="micro/mapper/Employee.xml" />


    </mappers>
</configuration>

Employee.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="micro.inter.EmployeeDao">
    <resultMap type="Employee" id="EmployeeList">
        <result column="id" property="id" />
        <result column="name" property="name" />
        <result column="age" property="age" />
        <result column="address" property="address" />
    </resultMap>

    <select id="selectEmployeeById" parameterType="int" resultType="Employee">
        select * from employee where #{id}
    </select>

    <select id="selectEmployees" resultMap="EmployeeList">
        select * from employee
    </select>

    <insert id="addEmployee" parameterType="Employee">
        insert into employee
        value(#{id},#{name},#{age},#{address})
    </insert>

    <update id="updateEmployee" parameterType="Employee">
        update employee set
        name = #{name},age = #{age},address = #{address} where id = #{id}
    </update>

    <delete id="deleteEmployee" parameterType="int">
        delete from employee
        where id = #{id}
    </delete>

    <!-- 第一种配置方法 -->
    <resultMap type="Project" id="EmloyeeProList">
        <result property="id" column="id" />
        <result property="name" column="name" />
        <!-- 
        <association property="employee" javaType="Employee">
            <result property="id" column="emid" />
            <result property="name" column="name" />
            <result property="address" column="address" />
        </association>  -->
        <!-- 第二种配置方法 -->
        <association property="employee" resultMap="EmployeeList"></association>
    </resultMap>
    <select id="selectEmloyeeProList" parameterType="int" resultMap="EmloyeeProList">
        select project.id,project.name,employee.id,employee.name,employee.address,employee.age from employee,project where employee.id = project.emid and employee.id = #{id}
    </select>
</mapper>

接口EmployeeDao:

package micro.inter;

import java.util.List;

import micro.model.Employee;
import micro.model.Project;

/**
@author:micro_hz
2015年8月19日
 */
public interface EmployeeDao {
    //定义 CUID
    //通过id查找
    public void selectEmployeeById(int id);
    //把所有对象放进列表
    public List<Employee> selectEmployees();
    //增加employee
    public void addEmployee(Employee employee);
    //删除employee
    public void deleteEmployee(int id);
    //改对应id的employee
    public void updateEmployee(Employee employee);
    //查找对应雇员的项目
    public List<Project> selectEmloyeeProList(int id);
}

测试:

//查到对应雇员id的所有项目
        List<Project> list = Service.getProjectsByEmid(2);
        for(Project project : list)
        {
            System.out.println("项目名字叫"+project.getName()+"项目负责的雇员为"+project.getEmployee().getId()+"项目的id为"+project.getId());
        }
### MyBatis 联合查询的使用方法 MyBatis 是一种优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。通过配置 XML 文件或注解来实现数据库操作。对于联合查询的支持,主要体现在 resultMap 和 association/collection 的使用上。 #### 使用 resultMap 实现一对一关联查询 当两个表之间存在外键关系时,可以定义 `resultMap` 来处理这种一对一双向或多向的关系。下面是一个简单的例子: 假设有一个订单表(Order)和客户表(Customer),其中 Order 表中有 customer_id 字段作为外键指向 Customer 表中的 id 字段,则可以在 Mapper.xml 中这样写: ```xml <resultMap type="com.example.Order" id="orderResult"> <id property="id" column="order_id"/> <result property="amount" column="amount"/> <!-- 关联对象 --> <association property="customer" javaType="com.example.Customer"> <id property="id" column="cust_id"/> <result property="name" column="cust_name"/> </association> </resultMap> <select id="getOrderByCustomerId" parameterType="int" resultMap="orderResult"> SELECT o.id as order_id, o.amount, c.id as cust_id, c.name as cust_name FROM orders o JOIN customers c ON o.customer_id = c.id WHERE o.customer_id=#{customerId} </select> ``` 这段代码展示了如何利用 `<association>` 标签指定子属性与父类之间的联系[^1]。 #### 多对多关联查询案例 如果涉及到多个实体间的复杂关系,比如学生选课系统中 Students 和 Courses 两张表间存在着多对多的关系,那么可以通过中间表 Student_Course 进行连接,并借助 collection 完成数据获取: ```xml <!-- 学生的结果集映射 --> <resultMap type="Student" id="studentWithCourses"> <collection property="courses" ofType="Course"> <id property="courseId" column="cid"/> <result property="title" column="ctitle"/> </collection> </resultMap> <select id="findStudentsByCourseTitle" parameterType="String" resultMap="studentWithCourses"> SELECT s.*, sc.cid, c.title AS ctitle FROM students s INNER JOIN student_course sc ON s.sid=sc.sid INNER JOIN courses c ON sc.cid=c.cid WHERE c.title LIKE CONCAT('%', #{title}, '%') </select> ``` 这里运用了 `<collection>` 元素表示集合类型的属性,用于表达一方拥有多方的情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值