首先,需要搭建MyBatis框架环境,包括导入MyBatis的依赖包以及配置MyBatis的配置文件。

  1. 导入MyBatis的依赖包(例如,使用Maven管理项目依赖):
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>
  1. 配置MyBatis的配置文件(例如,命名为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>
    <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/mydatabase"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/example/mapper/EmpMapper.xml"/>
        <mapper resource="com/example/mapper/DeptMapper.xml"/>
    </mappers>
</configuration>

注意替换urlusernamepassword为实际的数据库连接信息。

  1. 创建员工表Emp的映射文件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.example.mapper.EmpMapper">
    <resultMap id="EmpResultMap" type="com.example.model.Emp">
        <id property="empno" column="empno"/>
        <result property="ename" column="ename"/>
        <result property="hiredate" column="hiredate"/>
        <result property="sal" column="sal"/>
        <association property="dept" javaType="com.example.model.Dept">
            <id property="deptno" column="deptno"/>
            <result property="dname" column="dname"/>
            <result property="loc" column="loc"/>
        </association>
    </resultMap>

    <insert id="insertEmp" parameterType="com.example.model.Emp">
        INSERT INTO Emp (empno, ename, hiredate, sal, deptno)
        VALUES (#{empno}, #{ename}, #{hiredate}, #{sal}, #{dept.deptno})
    </insert>

    <select id="selectEmpByEmpnoAndEname" resultMap="EmpResultMap">
        SELECT empno, ename, hiredate, sal, deptno, dname, loc
        FROM Emp
        INNER JOIN dept ON Emp.deptno = dept.deptno
        WHERE empno LIKE CONCAT('%', #{empno}, '%')
        AND ename LIKE CONCAT('%', #{ename}, '%')
    </select>

    <select id="selectEmpByDeptnoAndDname" resultMap="EmpResultMap">
        SELECT empno, ename, hiredate, sal, deptno, dname, loc
        FROM Emp
        INNER JOIN dept ON Emp.deptno = dept.deptno
        WHERE dept.deptno LIKE CONCAT('%', #{deptno}, '%')
        AND dname LIKE CONCAT('%', #{dname}, '%')
    </select>
</mapper>
  1. 创建部门表Dept的映射文件DeptMapper.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.example.mapper.DeptMapper">
    <resultMap id="DeptResultMap" type="com.example.model.Dept">
        <id property="deptno" column="deptno"/>
        <result property="dname" column="dname"/>
        <result property="loc" column="loc"/>
        <collection property="employees" ofType="com.example.model.Emp">
            <id property="empno" column="empno"/>
            <result property="ename" column="ename"/>
            <result property="hiredate" column="hiredate"/>
            <result property="sal" column="sal"/>
        </collection>
    </resultMap>

    <insert id="insertDept" parameterType="com.example.model.Dept">
        INSERT INTO dept (deptno, dname, loc)
        VALUES (#{deptno}, #{dname}, #{loc})
    </insert>

    <select id="selectDeptByDeptnoAndDname" resultMap="DeptResultMap">
        SELECT deptno, dname, loc, empno, ename, hiredate, sal
        FROM dept
        INNER JOIN Emp ON dept.deptno = Emp.deptno
        WHERE dept.deptno LIKE CONCAT('%', #{deptno}, '%')
        AND dname LIKE CONCAT('%', #{dname}, '%')
    </select>
</mapper>
  1. 创建员工类Emp
package com.example.model;

public class Emp {
    private Integer empno;
    private String ename;
    private Date hiredate;
    private Double sal;
    private Dept dept;

    // getters and setters
}
  1. 创建部门类Dept
package com.example.model;

public class Dept {
    private Integer deptno;
    private String dname;
    private String loc;
    private List<Emp> employees;

    // getters and setters
}
  1. 创建EmpMapper接口:
package com.example.mapper;

import com.example.model.Emp;

public interface EmpMapper {
    void insertEmp(Emp emp);
    List<Emp> selectEmpByEmpnoAndEname(String empno, String ename);
    List<Emp> selectEmpByDeptnoAndDname(String deptno, String dname);
}
  1. 创建DeptMapper接口:
package com.example.mapper;

import com.example.model.Dept;

public interface DeptMapper {
    void insertDept(Dept dept);
    List<Dept> selectDeptByDeptnoAndDname(String deptno, String dname);
}
  1. 使用MyBatis进行查询:
package com.example;

import com.example.mapper.EmpMapper;
import com.example.mapper.DeptMapper;
import com.example.model.Emp;
import com.example.model.Dept;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        try {
            // 加载MyBatis配置文件
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // 创建SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();

            // 获取Mapper接口的实例
            EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
            DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);

            // 新增员工和部门
            Dept dept = new Dept();
            dept.setDeptno(1);
            dept.setDname("部门A");
            dept.setLoc("地址A");
            deptMapper.insertDept(dept);

            Emp emp = new Emp();
            emp.setEmpno(1);
            emp.setEname("员工A");
            emp.setHiredate(new Date());
            emp.setSal(1000.0);
            emp.setDept(dept);
            empMapper.insertEmp(emp);

            // 根据条件查询员工
            String empno = "1";
            String ename = "员工";
            List<Emp> empList = empMapper.selectEmpByEmpnoAndEname(empno, ename);
            for (Emp e : empList) {
                System.out.println("员工编号:" + e.getEmpno());
                System.out.println("员工姓名:" + e.getEname());
                System.out.println("入职日期:" + e.getHiredate());
                System.out.println("薪水:" + e.getSal());
                System.out.println("所属部门编号:" + e.getDept().getDeptno());
                System.out.println("所属部门名称:" + e.getDept().getDname());
                System.out.println("所属部门地址:" + e.getDept().getLoc());
                System.out.println("--------------------");
            }

            // 根据条件查询部门
            String deptno = "1";
            String dname = "部门";
            List<Dept> deptList = deptMapper.selectDeptByDeptnoAndDname(deptno, dname);
            for (Dept d : deptList) {
                System.out.println("部门编号:" + d.getDeptno());
                System.out.println("部门名称:" + d.getDname());
                System.out.println("部门地址:" + d.getLoc());
                System.out.println("部门员工列表:");
                for (Emp e : d.getEmployees()) {
                    System.out.println("员工编号:" + e.getEmpno());
                    System.out.println("员工姓名:" + e.getEname());
                    System.out.println("入职日期:" + e.getHiredate());
                    System.out.println("薪水:" + e.getSal());
                    System.out.println("--------------------");
                }
                System.out.println("--------------------");
            }

            // 提交事务
            sqlSession.commit();

            // 关闭资源
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

以上代码演示了如何使用MyBatis框架搭建环境,并实现了部门和员工表的查询功能。注意根据实际情况修改数据库连接信息和查询条件,以及其他相关配置


原文地址: https://www.cveoy.top/t/topic/iGZV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录