MyBatis關聯查詢:多對一

數據表

在這裏插入圖片描述

項目框架搭建

第一步:創建Maven項目

  • 添加Maven依賴:
<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.18</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.4</version>
    </dependency>
  • 指定Mapper XML文件在mybatis-config.xml中的配置有效,強制部署resources目錄到classes
<resources>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
    <resource>
        <directory>${basedir}/src/main/resources</directory>
    </resource>
</resources>

第二步:配置文件

  • log4j.properties
log4j.rootLogger=DEBUG, Console  

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  

log4j.logger.java.sql.ResultSet=INFO  
log4j.logger.org.apache=INFO  
log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG  
  • mysql.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1/db_test?useSSL=false&serverTimezone=CST
username=root
password=root

第三步:工具類MyBatisUtil

public class MyBatisUtil {
    private static String CONFIG_FILE_LOCATION = "mybatis-config.xml";
    private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sessionFactory;

    static {
        try {
            Reader reader = Resources.getResourceAsReader(CONFIG_FILE_LOCATION);
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            sessionFactory = builder.build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession() {
        SqlSession session = threadLocal.get();
        if (session == null) {
            session = (sessionFactory != null) ? sessionFactory.openSession() : null;
            threadLocal.set(session);
        }
        return session;
    }

    public static void closeSession() {
        SqlSession session = threadLocal.get();
        if (session != null) {
            session.close();
            threadLocal.set(null);
        }
    }
}

第四步:實體類

  • Dept
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Dept implements Serializable {

    private static final long serialVersionUID = -4186854135138751084L;

    private Integer deptno;
    private String dname;
    private String loc;

}

  • Emp
@Data
@ToString(exclude = "dept") //設置toString輸出字段中不包含emps字段
@AllArgsConstructor
@NoArgsConstructor
public class Emp implements Serializable {

	private static final long serialVersionUID = 4976291764719306570L;

	private Integer empno;  //封裝數據類型
	private String ename;
	private String job;
	private Integer mgr;  //封裝數據類型
	private LocalDate hiredate;
	private Double sal;
	private Double comm;
	private Integer deptno;
	
	////////////////////////////////////////
	private Dept dept;
}

XML方式

第一步:創建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文件  -->
    <properties resource="mysql.properties"></properties>

    <settings>
        <!-- 打印查詢語句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">  <!-- 數據源的配置,連接到數據庫 -->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/hc/dao/EmpMapper.xml"/>
    </mappers>
</configuration>

注意:mappers標籤中使用的是resouce

第二步:DeptDao

public interface EmpDao {
    Emp selectEmpWithDeptByEmpno(int Empno);
}

第三步: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.hc.dao.EmpDao">

    <resultMap type="com.hc.bean.Emp" id="empDept">
        <id property="empno" column="empno" />
        <result property="ename" column="ename" />
        <result property="job" column="job" />
        <result property="mgr" column="mgr" />
        <result property="hiredate" column="hiredate" />
        <result property="sal" column="sal" />
        <result property="comm" column="comm" />
        <association property="dept" javaType="com.hc.bean.Dept">
            <id property="deptno" column="deptno" />
            <result property="dname" column="dname" />
            <result property="loc" column="loc" />
        </association>
    </resultMap>

    <select id="selectEmpWithDeptByEmpno" parameterType="int" resultMap="empDept">
        select * from tb_emp
        inner join tb_dept
        on tb_emp.deptno = tb_dept.deptno
        WHERE empno = #{empno};
    </select>

</mapper>

測試代碼

public class EmpDaoTest {

    @Test
    public void getEmpWithDeptByEmpno() {
        SqlSession session = MyBatisUtil.getSession();
        EmpDao empDao= session.getMapper(EmpDao.class);
        Emp emp = empDao.selectEmpWithDeptByEmpno(7788);
        System.out.println(emp);
        System.out.println(emp.getDept());
    }

}

註解方式

第一步:創建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文件  -->
    <properties resource="mysql.properties"></properties>

    <settings>
        <!-- 打印查詢語句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">  <!-- 數據源的配置,連接到數據庫 -->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
		<mapper class="com.hc.many2one.dao.DeptDao"/>
        <mapper class="com.hc.many2one.dao.EmpDao"/>
    </mappers>
</configuration>

第二步:創建Dao接口

  • DeptDao
public interface DeptDao {

    @Select("select * from tb_dept where deptno= #{deptno}")
    Dept selectDeptByDeptno(Integer deptno);
}

  • EmpDao
public interface EmpDao {
      @Select("select * from tb_emp where empno = #{empno}")
      @Results({
            @Result(
                    property = "dept",column = "deptno",
                    one = @One(select = "com.hc.many2one.dao.DeptDao.selectDeptByDeptno")
            )
      })
      Emp selectEmpByEmpno(Integer empno);
}

測試代碼

public class EmpDaoTest {

    //多對一
    @Test
    public void selectEmpByEmpno(){
        SqlSession session = MyBatisUtil.getSession();
        EmpDao empDao = session.getMapper(EmpDao.class);
        Emp emp = empDao.selectEmpByEmpno(7788);
        System.out.println(emp);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章