一对一关系实现员工—>部门的查询

resutlType和resultMap的使用(参考文档)

在这里插入图片描述

实现部门和员工的查询: (参考代码)

EmpMapper.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="com.yzh7.mapper.EmpMapper">

    <resultMap id="empMap" type="emp" autoMapping="true">
        <!--id:表示表中的主键字段  column:查询表的列名 property:表示列名要映射到的实体属性-->
        <id column="emp_id" property="empId"/>
        <!--result:定义普通列和属性的映射关系-->
        <result column="emp_name" property="empName"/>
        <result column="sex" property="sex"/>
        <result column="phone" property="phone"/>
        <!--通过association标签(1对1),设置员工关联的部门对象-->
        <association property="dept" javaType="Dept" autoMapping="true">
            <id column="dept_id" property="deptId"/>
            <result column="dept_name" property="deptName"/>
            <result column="description" property="description"/>
        </association>
    </resultMap>

    <!--
    resultType:只用于单表查询,并且查询结果列名和属性可以直接对应的情况。用于简单查询映射。
    resultMap:用于多表查询,或者列名和属性映射关系负责的情况。用于复杂查询映射。
              需要通过resultMap节点,配置结果的映射关系
    -->
    <select id="listAll" resultMap="empMap">
        select e.emp_id,e.emp_name,e.sex,e.phone,
               d.dept_id,d.dept_name,d.description
        from t_emp e
        join t_dept d
        on e.dept_id = d.dept_id
    </select>
</mapper>

一对一关系实现部门和员工的查询:

效果图展示:

创建数据库/表:

在这里插入图片描述

在这里插入图片描述

代码运行结果:

在这里插入图片描述

项目实现思路(参考):

在这里插入图片描述

代码整体布局:

在这里插入图片描述
注意:

在这里插入图片描述

代码:

创建数据库/表:
#创建部门表
create table t_dept 
( 
	dept_id int primary key auto_increment comment '部门编号', 
	dept_name varchar(20) comment '部门名字', 
	description varchar(200) comment '描述' 
);

select * from t_dept;

insert into t_dept
(dept_name,description)
select '财务部','管钱的' union
select '后勤部','搞物业' union
select 'IT部门','编程序';


#创建员工表
create table t_emp 
( 
	emp_id int primary key auto_increment comment '员工编号', 
	emp_name varchar(20) comment '员工姓名', 
	sex char(1) comment '性别', 
	phone varchar(11) comment '手机号', 
-- 	hireDate date comment '入职日期', 
-- 	leaveDate date comment '离职日期', 
-- 	address varchar(200) comment '家庭住址', 
-- 	username varchar(20) comment '员工账号', 
-- 	password varchar(20) comment '员工密码', 
	dept_id int comment '所属部门' 
);

select * from t_emp;

insert into t_emp
(emp_name,sex,phone,dept_id)
select '张三','女','1234567890',1 union
select '李四','男','1234567891',1 union
select '王五','女','1234567892',2 union
select '赵六','男','1234567893',3 ;
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mybatis_0815_KTLX</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <!--引入jar包-->
    <dependencies>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <!-- mysql驱动类 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>
db.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/70813_db?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=123456
mybatis_config.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>
    <properties resource="db.properties"></properties>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <typeAliases>
        <package name="com.yzh7.entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--定义关联的mapper接口,通过三一致的规则自动与mapper文件关联-->
        <mapper class="com.yzh7.mapper.BookMapper"/>
        <mapper class="com.yzh7.mapper.EmpMapper"/>

    </mappers>
</configuration>

参考官网:mybatis映射器mappers
https://mybatis.org/mybatis-3/zh/configuration.html#mappers
在这里插入图片描述

Dept:
package com.yzh7.entity;

import lombok.Data;

import java.util.List;

@Data
public class Dept {
    private Integer deptId;
    private String deptName;
    private String description;

    //一个部门拥有多个员工
    private List<Emp> empList;
}

Emp:
package com.yzh7.entity;

import lombok.Data;

@Data
public class Emp {
    private Integer empId;
    private String empName;
    private String sex;
    private String phone;
    private Integer deptId;

    //一个员工属于一个部门
    private Dept dept;
}

DeptMapper:
package com.yzh7.mapper;

import com.yzh7.entity.Dept;

import java.util.List;

public interface DeptMapper {
    //查询部门,一个部门关联多个员工
    List<Dept> listAll();
}

EmpMapper:
package com.yzh7.mapper;

import com.yzh7.entity.Emp;

import java.util.List;

public interface EmpMapper {
    //查询所有员工,并且每个员工关联一个部门对象
    List<Emp> listAll();

}

EmpMapper.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="com.yzh7.mapper.EmpMapper">


    <resultMap id="empMap" type="emp">
<!-- emp_id,emp_name,sex,phone,dept_id-->

        <!--id:表示表中的主键字段  column:查询表的列名 property:表示列名要映射到的实体属性-->
        <id column="emp_id" property="empId"/>

        <!--result:定义普通列和属性的映射关系-->
        <result column="emp_name" property="empName"/>
        <result column="sex" property="sex"/>
        <result column="phone" property="phone"/>
        <result column="dept_id" property="deptId"/>

<!-- dept_id,dept_name,description-->
        <!--通过association标签(1对1),设置员工关联的部门对象-->
        <association property="dept" javaType="Dept">

            <id column="dept_id" property="deptId"/>
            <result column="dept_name" property="deptName"/>
            <result column="description" property="description"/>
        </association>
    </resultMap>
    
        <!--
            resultType:只用于单表查询,并且查询结果列名和属性可以直接对应的情况。用于简单查询映射。
            resultMap:用于多表查询,或者列名和属性映射关系负责的情况。用于复杂查询映射。
            需要通过resultMap节点,配置结果的映射关系
         -->
    <select id="listAll" resultMap="empMap">
        select e.emp_id,e.emp_name,e.sex,e.phone,
                d.dept_id,d.dept_name,d.description
        from t_emp e
        join t_dept d
        on e.dept_id=d.dept_id
    </select>

</mapper>
或者:
EmpMapper.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="com.yzh7.mapper.EmpMapper">


<!--    <resultMap id="empMap" type="emp">-->
<!--&lt;!&ndash; emp_id,emp_name,sex,phone,dept_id&ndash;&gt;-->

<!--        &lt;!&ndash;id:表示表中的主键字段  column:查询表的列名 property:表示列名要映射到的实体属性&ndash;&gt;-->
<!--        <id column="emp_id" property="empId"/>-->

<!--        &lt;!&ndash;result:定义普通列和属性的映射关系&ndash;&gt;-->
<!--        <result column="emp_name" property="empName"/>-->
<!--        <result column="sex" property="sex"/>-->
<!--        <result column="phone" property="phone"/>-->
<!--        <result column="dept_id" property="deptId"/>-->

<!--&lt;!&ndash; dept_id,dept_name,description&ndash;&gt;-->
<!--        &lt;!&ndash;通过association标签(1对1),设置员工关联的部门对象&ndash;&gt;-->
<!--        <association property="dept" javaType="Dept">-->

<!--            <id column="dept_id" property="deptId"/>-->
<!--            <result column="dept_name" property="deptName"/>-->
<!--            <result column="description" property="description"/>-->
<!--        </association>-->
<!--    </resultMap>-->


    <resultMap id="empMap" type="emp" autoMapping="true">
        <!-- emp_id,emp_name,sex,phone,dept_id-->

        <!--id:表示表中的主键字段  column:查询表的列名 property:表示列名要映射到的实体属性-->
        <id column="emp_id" property="empId"/>

        <!--result:定义普通列和属性的映射关系-->
<!--        <result column="emp_name" property="empName"/>-->
<!--        <result column="sex" property="sex"/>-->
<!--        <result column="phone" property="phone"/>-->
<!--        <result column="dept_id" property="deptId"/>-->

        <!-- dept_id,dept_name,description-->
        <!--通过association标签(1对1),设置员工关联的部门对象-->
        <association property="dept" javaType="Dept" autoMapping="true">

            <id column="dept_id" property="deptId"/>
<!--            <result column="dept_name" property="deptName"/>-->
<!--            <result column="description" property="description"/>-->
        </association>
    </resultMap>
    
        <!--
            resultType:只用于单表查询,并且查询结果列名和属性可以直接对应的情况。用于简单查询映射。
            resultMap:用于多表查询,或者列名和属性映射关系负责的情况。用于复杂查询映射。
            需要通过resultMap节点,配置结果的映射关系
         -->
    <select id="listAll" resultMap="empMap">
        select e.emp_id,e.emp_name,e.sex,e.phone,
                d.dept_id,d.dept_name,d.description
        from t_emp e
        join t_dept d
        on e.dept_id=d.dept_id
    </select>

</mapper>
demo3:
package com.yzh7.test;

import com.yzh7.entity.Emp;
import com.yzh7.mapper.EmpMapper;
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.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class demo3 {


    @Test
    public void test1(){
        EmpMapper empMapper=session.getMapper(EmpMapper.class);
        List<Emp> empList=empMapper.listAll();
        for(Emp e:empList){
            System.out.println(e);
        }
    }


    private static SqlSessionFactory factory;    //静态
    private SqlSession session;

    @BeforeClass
    public static void befCla() throws IOException {
        String resource = "mybatis_config.xml";   //mybatis_config.xml
        InputStream inputStream = Resources.getResourceAsStream(resource);
        factory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Before
    public void bf(){
        session=factory.openSession();
    }

    @After
    public void af(){
        session.commit();
        session.close();
    }
}

// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要建立一个员工信息类和一个部门信息类,代码如下: ```java public class Employee { private int id; private String name; private String department; public Employee(int id, String name, String department) { this.id = id; this.name = name; this.department = department; } // getter and setter methods } public class Department { private String name; private String location; public Department(String name, String location) { this.name = name; this.location = location; } // getter and setter methods } ``` 接下来,我们需要建立一个员工信息部门信息的映射关系类,代码如下: ```java public class EmployeeDepartmentMap { private Map<Integer, Employee> employeeMap; private Map<String, Department> departmentMap; public EmployeeDepartmentMap() { employeeMap = new HashMap<>(); departmentMap = new HashMap<>(); // 假设已经有预先设定的员工信息部门信息 employeeMap.put(1, new Employee(1, "Tom", "Finance")); employeeMap.put(2, new Employee(2, "Jerry", "Marketing")); employeeMap.put(3, new Employee(3, "Bob", "HR")); departmentMap.put("Finance", new Department("Finance", "Beijing")); departmentMap.put("Marketing", new Department("Marketing", "Shanghai")); departmentMap.put("HR", new Department("HR", "Guangzhou")); } public Employee getEmployeeById(int id) { return employeeMap.get(id); } public Department getDepartmentByEmployee(Employee employee) { return departmentMap.get(employee.getDepartment()); } } ``` 最后,我们可以在主函数中使用上述类获取员工信息和对应的部门信息,代码如下: ```java public class Main { public static void main(String[] args) { EmployeeDepartmentMap map = new EmployeeDepartmentMap(); Employee employee = map.getEmployeeById(1); Department department = map.getDepartmentByEmployee(employee); System.out.println("Employee: " + employee.getName() + ", Department: " + department.getName() + ", Location: " + department.getLocation()); } } ``` 输出结果为: ``` Employee: Tom, Department: Finance, Location: Beijing ``` 注意,上述代码只是一个简单的示例,实际情况中需要根据具体需求进行适当的修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值