欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MyBatis基础-07-mybatis一对多关联查询

程序员文章站 2022-04-22 22:18:04
...

pom.xml

 <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>com.monkey1024</groupId>
  <artifactId>01mybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
	  	<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.4.6</version>
		</dependency>
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>5.1.46</version>
		</dependency>
		<dependency>
		    <groupId>log4j</groupId>
		    <artifactId>log4j</artifactId>
		    <version>1.2.17</version>
		</dependency>
		<dependency>
		  <groupId>commons-io</groupId>
		  <artifactId>commons-io</artifactId>
		  <version>2.6</version>
		</dependency>
		<dependency>
		  <groupId>commons-fileupload</groupId>
		  <artifactId>commons-fileupload</artifactId>
		  <version>1.3.3</version>
		</dependency>
		<dependency>
		   <groupId>org.hibernate</groupId>
		   <artifactId>hibernate-validator</artifactId>
		   <version>6.0.9.Final</version>
		</dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>

    </dependencies>
    <build>
    	<!-- 与工程名一致 -->
        <finalName>01mybatis</finalName>
        <resources>
        	<resource>
        		<directory>src/main/java</directory>
        		<includes>
        			<include>**/*.xml</include>
        		</includes>
        	</resource>
        </resources>
        <plugins>
            <!-- 编译插件,指定编译用的的jdk版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <!-- jdk的版本号 -->
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

mybatis.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>

	<!-- 注册db配置文件 -->
	<properties resource="db.properties"/>
	
	<!-- mybatis配置文件中的标签是有顺序的 -->
	<!-- 注册实体类的权限定义名的别名 -->
	<typeAliases>
		<!-- 方式一:这种方式配置不太方便 -->
		<typeAlias type="com.monkey1024.bean.Student" alias="student"/>
		<!-- 方式二:mybatis会在这个包下搜索需要的javabean -->
		<package name="com.monkey1024.bean"/>
	</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.user}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--注册映射文件-->
        <mapper resource="com/monkey1024/dao/TeamMapper.xml"/>
    </mappers>
</configuration>

TeamMapper.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.monkey1024.dao.TeamDao">

	<resultMap id="teamMap" type="team">
		<!-- 篮球队的属性 -->
		<id column="teamid" property="id"/>
		<result column="tname" property="name"/>
		
		<!-- 关联属性的映射关系 -->
		<collection property="playerList" ofType="player">
			<id column="pid" property="id"/>
			<result column="pname" property="name"/>
		</collection>
	</resultMap>

	<select id="selectTeamById" resultMap="teamMap">
		select t.id teamid,t.name tname,p.id pid,p.name pname
		from t_team t,t_player p
		where t.id=p.tid and t.id=#{id}
	</select>
</mapper>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/learnmybatis?useSSL=false
jdbc.user=root
jdbc.password=666666

log4j.properties

log4j.rootLogger=debug,console
#log4j.logger.com.monkey1024.dao.StudentDao=debug,concole
#\u63A7\u5236\u53F0\u9644\u52A0\u5668
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = [%-5p][%d{yyyy-MM--dd HH:mm:ss}]%m%n

Player.java 

package com.monkey1024.bean;



/*
 * 篮球队员
 */
public class Player {	
	private int id;
	private String name;
	public Player(String name){
		this.name = name;
	}
	public Player(){
		
	}
	@Override
	public String toString() {
		return "Player [id=" + id + ", name=" + 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;
	}

}

Team.java

package com.monkey1024.bean;

import java.util.List;

/*
 * 篮球队
 */
public class Team {
	private int id;
	private String name;
	private List<Player> playerList;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	@Override
	public String toString() {
		return "Team [id=" + id + ", name=" + name + ", playerList=" + playerList + "]";
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public List<Player> getPlayerList() {
		return playerList;
	}
	public void setPlayerList(List<Player> playerList) {
		this.playerList = playerList;
	}
	
}

TeamDao.java

package com.monkey1024.dao;

import com.monkey1024.bean.Team;

public interface TeamDao {
	Team selectTeamById(int id);
}

MyBatisUtil.java

package com.monkey1024.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/*
 * DCL鐨勫崟渚嬫ā寮�
 */
public class MyBatisUtil {
	// 鏃犻渶灏嗘瀯閫犳柟娉曠鏈夊寲锛屽洜涓鸿繖閲岄潰鍙淇濊瘉鍒涘缓涓�涓猄qlSessionFactory鐨勫璞�
	// private MyBatisUtil()
	private static volatile SqlSessionFactory sqlSessionFactory;

	public static SqlSession getSqlSession() {
		try {
			if (sqlSessionFactory == null) {
				// 璇诲彇涓婚厤缃枃浠�
				InputStream input = Resources.getResourceAsStream("mybatis.xml");
				synchronized (MyBatisUtil.class) {
					if (sqlSessionFactory == null) {
						sqlSessionFactory = new SqlSessionFactoryBuilder().build(input);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		//mybatis鑷姩鎻愪氦浜嬪姟
//		return sqlSessionFactory.openSession(true);
		return sqlSessionFactory.openSession();

	}
}

TeamTest01.java

package com.monkey1024.test;

import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.monkey1024.bean.Team;
import com.monkey1024.dao.TeamDao;
import com.monkey1024.util.MyBatisUtil;

public class TeamTest01 {
	private SqlSession sqlSession;
	private TeamDao teamDao;
	
	@Before
	public void init(){
		sqlSession = MyBatisUtil.getSqlSession();
		teamDao = sqlSession.getMapper(TeamDao.class);
	}
	
	@After 
	public void closeSession(){
		if(sqlSession!=null){
			sqlSession.close();
		}
	}
	
	@Test
	public void selectTeamById(){
		Team team = teamDao.selectTeamById(1);
		System.out.println(team);
	}
	
}