MyBatis-多对一查询

  1. 云栖社区>
  2. 博客>
  3. 正文

MyBatis-多对一查询

技术小美 2017-11-12 17:07:00 浏览587
展开阅读全文


本文转自 素颜猪 51CTO博客,原文链接:http://blog.51cto.com/suyanzhu/1916923



1.创建Maven项目,项目名称mybatisdemo1,目录结构如图所示

wKiom1j1eb3ja5VnAAArdk0bccQ064.png-wh_50


2.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.mycompany</groupId>
  <artifactId>mybatisdemo1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build/>
  
  <dependencies>
  	<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
	<dependency>
	    <groupId>org.apache.logging.log4j</groupId>
	    <artifactId>log4j-core</artifactId>
	    <version>2.7</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.4.1</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.39</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/junit/junit -->
	<dependency>
	    <groupId>junit</groupId>
	    <artifactId>junit</artifactId>
	    <version>4.11</version>
	</dependency>
	
	
  </dependencies>
  
  
</project>


3.在src/main/java目录创建实体类Forum,包名(com.mycompany.beans),目录结构如下

wKiom1j1ekKAJDgUAAA-4OiJi8o503.png-wh_50


4.实体类Forum的内容如下

package com.mycompany.beans;

public class Forum {
	private Integer fid;
	private String name;
	
	public Forum() {
		super();
	}
	public Forum(String name) {
		super();
		this.name = name;
	}
	public Forum(Integer fid, String name) {
		super();
		this.fid = fid;
		this.name = name;
	}
	public Integer getFid() {
		return fid;
	}
	public void setFid(Integer fid) {
		this.fid = fid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}


5.在src/main/java目录创建实体类Forumpost,包名(com.mycompany.beans),目录结构如下

wKioL1j1epvhOwD9AABC823NJDY102.png-wh_50


6.实体类Forumpost的内容如下

package com.mycompany.beans;

public class Forumpost {
	private Integer pid;
	private String subject;
	private Forum forum;
	
	public Forumpost() {
		super();
	}
	public Forumpost(String subject, Forum forum) {
		super();
		this.subject = subject;
		this.forum = forum;
	}
	public Forumpost(Integer pid, String subject, Forum forum) {
		super();
		this.pid = pid;
		this.subject = subject;
		this.forum = forum;
	}
	public Integer getPid() {
		return pid;
	}
	public void setPid(Integer pid) {
		this.pid = pid;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public Forum getForum() {
		return forum;
	}
	public void setForum(Forum forum) {
		this.forum = forum;
	}
	@Override
	public String toString() {
		return "[pid="+pid+",subject="+subject+",
		forum[fid="+forum.getFid()+",name="+forum.getName()+"]]";
	}
	
}


7.在src/main/java目录创建接口ForumpostMapper,包名(com.mycompany.mapper),目录结构如下

wKioL1j1e1PSDL0KAABALEXS1Fo437.png-wh_50


8.接口ForumpostMapper的内容如下

package com.mycompany.mapper;

import java.util.List;

import com.mycompany.beans.Forumpost;

public interface ForumpostMapper {
	
	/**
	 * 根据分类编号查询所有的话题信息
	 * @return
	 * @throws Exception
	 */
	public List<Forumpost> selectAllByFid(int fid) throws Exception;
}


9.在src/main/java目录创建映射文件ForumpostMapper.xml,包名(com.mycompany.mapper),目录结构如下

wKioL1j1e8Szu00dAABFt4E-G-0349.png-wh_50


10.映射文件ForumpostMapper.xml的内容如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mycompany.mapper.ForumpostMapper">
	
	<!-- 查询所有信息 -->
	<select id="selectAllByFid" resultMap="getForumPostListByFid" parameterType="int">
		select 
			f.fid,f.name,p.pid,p.subject 
		from
			forum f,forumpost p
		where
			f.fid  = p.fid
		and
			f.fid = #{fid}
	</select>
	
	<resultMap type="Forumpost" id="getForumPostListByFid">
		<id property="pid" column="pid" javaType="java.lang.Integer"/>
		<result property="subject" column="subject" javaType="java.lang.String"/>
		
		<association property="forum" javaType="Forum">
			<id property="fid" column="fid"/>
			<result property="name" column="name"/>
		</association>
	</resultMap>
</mapper>


11.在src/main/resources下创建mysql.properties属性文件,目录结构如下

wKioL1j1fDuCZrbYAAA0ZJBsbW0278.png-wh_50


12.mysql.properties属性文件的内容如下

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=


13.在src/main/resources下创建mybatis.cfg.xml配置文件,目录结构如下

wKiom1j1fKbDAHmpAAA4tw847ac072.png-wh_50


14.mybatis.cfg.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="mysql.properties"></properties>
  	
  	<typeAliases>
  		<package name="com.mycompany.beans"/>
  	</typeAliases>
  	
  	<!-- 配置mybatis运行环境 -->
    <environments default="mybatis">
		<environment id="mybatis">
			<!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
            <transactionManager type="JDBC" />
            <!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI -->
            <!-- POOLED 表示支持JDBC数据源连接池 -->
            <!-- UNPOOLED 表示不支持数据源连接池 -->
            <!-- JNDI 表示支持外部数据源连接池 -->
            <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>
     	<package name="com/mycompany/mapper"/>
     </mappers>
     
</configuration>


15.在src/main/java下创建工具类DBUtils,包名(com.mycompany.util)目录结构如下

wKiom1j1fRKxBBu0AAA6UhNkf4w363.png-wh_50


16.工具类DBUtils的内容如下

package com.mycompany.util;

import java.io.IOException;
import java.io.Reader;


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

public class DBUtils {
	public static SqlSessionFactory sessionFactory;
	
	static{
		try {
			Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
			sessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static SqlSession getSession(){
		return sessionFactory.openSession();
	}
}


17.在src/main/java下创建业务类ForumpostService,包名(com.mycompany.service)目录结构如下

wKiom1j1fXfAaoQ8AAA7vI2n-Dk423.png-wh_50


18.业务类ForumpostService的内容如下

package com.mycompany.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.mycompany.beans.Forumpost;
import com.mycompany.mapper.ForumpostMapper;
import com.mycompany.util.DBUtils;

public class ForumpostService {
	
	/**
	 * 查询所有信息
	 */
	public void selectAll(){
		SqlSession session = DBUtils.getSession();
		ForumpostMapper mapper = session.getMapper(ForumpostMapper.class);
		try {
			List<Forumpost> forumposts = mapper.selectAllByFid(12);
			for (Forumpost forumpost : forumposts) {
				System.out.println(forumpost);
			}
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}
	}
}


19.在src/test/java下创建测试类ForumpostServiceTest,包名(com.mycompany.service),目录结构如下

wKiom1j1fiLBx_WEAAA1V1wOYCo241.png-wh_50


20.测试类ForumpostServiceTest的内容如下

package com.mycompany.service;

import org.junit.Test;

public class ForumpostServiceTest {

	/**
	 * 测试查询所有信息
	 */
	@Test
	public void selectAll(){
		ForumpostService forumpostService = new ForumpostService();
		forumpostService.selectAll();
	}
}

wKioL1j1fkuzvkgbAABwCKMO5XE098.png-wh_50

网友评论

登录后评论
0/500
评论
技术小美
+ 关注