来实现 MyBatis 中连接池的配置。在这三种数据源中,我们一般采用的是 POOLED 数据源。
MyBatis核心配置文件:
<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>
1234567
的 type 属性来创建相应类型的的数据源 DataSource,即:type="POOLED"
:MyBatis 会创建 PooledDataSource 实例type="UNPOOLED"
: MyBatis 会创建 UnpooledDataSource 实例type="JNDI"
:MyBatis 会从 JNDI 服务上查找 DataSource 实例,然后返回使用getDataSource()
方法返回数据源DataSource。MyBatis核心配置文件:
<dataSource type="UNPOOLED">
<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>
JNDI:Java Naming and Directory Interface,Java命名和目录接口。是SUN公司推出的一套规范,属于JavaEE技术之一。目的是模仿windows系统中的注册表在服务器中注册数据源。
创建Maven的war工程并导入依赖:
配置自己安装的Maven版本(也可以选择默认的版本):
导入依赖:
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.6version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.12version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.10version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
dependency>
dependencies>
在src/main下创建java、resource目录,并标记为对应的目录类型:
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public Date getUserBirthday() {
return userBirthday;
}
public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAddress='" + userAddress + '\'' +
", userSex='" + userSex + '\'' +
", userBirthday=" + userBirthday +
'}';
}
}
IUserDao:
import com.fox.pojo.User;
import java.util.List;
public interface IUserDao {
//查询所有用户
List<User> findAll();
}
1234567
IUserDao.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fox.dao.IUserDao">
<select id="findAll" resultType="com.fox.pojo.User">
select * from user;
select>
mapper>
jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
log4j.properties:
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
在webapp文件下创建META-INF目录,并在META-INF目录中建立一个名为context.xml的配置文件:
<Context>
<Resource
name="jdbc/test"
type="javax.sql.DataSource"
auth="Container"
maxActive="20"
maxWait="10000"
maxIdle="5"
username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
/>
Context>
配置 MyBatis 核心配置文件SqlMapConfig.xml,数据源写JNDI:
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties">properties>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC">transactionManager>
<dataSource type="JNDI">
<property name="data_source" value="java:comp/env/jdbc/test"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/fox/dao/IUserDao.xml" />
mappers>
configuration>
在WEB-INF下的index.jsp中写测试代码(因为只有这样才会经过Tomcat服务器 ):
<%@ page import="org.apache.ibatis.io.Resources" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactoryBuilder" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactory" %>
<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="com.fox.dao.IUserDao" %>
<%@ page import="com.fox.pojo.User" %>
<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<h2>Hello World!h2>
<%
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.根据配置文件构建SqlSessionFactory
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用SqlSessionFactory创建SqlSession对象
SqlSession sqlSession = factory.openSession();
//4.使用SqlSession构建Dao的代理对象
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
//5.执行dao中的findAll方法
List<User> users = userDao.findAll();
for(User user : users){
System.out.println(user);
}
//6.释放资源
sqlSession.close();
in.close();
%>
body>
html>
在 JDBC 中我们可以通过手动方式将事务的提交改为手动方式,通过 setAutoCommit()
方法就可以调整。那么我们的 Mybatis 框架因为是对 JDBC 的封装,所以 Mybatis 框架的事务控制方式,本身也是用 JDBC 的setAutoCommit()
方法来设置事务提交方式的。
MyBatis是通过sqlsession对象的commit()
方法和rollback()
方法实现事务的提交和回滚。
手动提交事务:sqlSession.commit();
我们运行之前所写的代码:
import com.fox.dao.IUserDao;
import com.fox.pojo.User;
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.Test;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest {
private InputStream in = null;
private SqlSession sqlSession =null;
private IUserDao userDao = null;
@Before //标记在非静态方法上。在@Test方法前面执行,而且是在每一个@Test方法前面都执行。
public void init() throws IOException {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.使用构建者创建工厂对象 SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.使用 SqlSessionFactory 生产 SqlSession 对象
sqlSession = factory.openSession();
//4.使用 SqlSession 创建 dao 接口的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After //标记在非静态方法上。在@Test方法后面执行,而且是在每一个@Test方法后面都执行。
public void destroy() throws IOException {
//增删改,记得提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
in.close();
}
@Test
public void testAddUser(){
User user = new User();
//由于id是自增的,所以没有id
user.setUserName("小黑");
user.setBirthday(new Date());
user.setUserAddress("上海");
user.setSex("男");
userDao.addUser(user);
}
}
观察在它在控制台输出的结果:
这是我们的 Connection 的整个变化过程,通过分析我们能够发现之前的 CUD 操作过程中,我们都要手动进行事务的提交,原因是在执行前 setAutoCommit()
方法它的值被设置为 false 了,所以我们在 CUD 操作中,必须通过 sqlSession.commit()
方法来执行提交操作。
通过上面的研究和分析,现在我们一起思考,为什么 CUD 过程中必须使用 sqlSession.commit()
提交事务?主要原因就是在连接池中取出的连接,都会将调用 connection.setAutoCommit(false)
方法,这样我们就必须使用 sqlSession.commit()
方法,相当于使用了 JDBC 中的 connection.commit()
方法实现事务提交。
自动提交事务:SqlSession sqlSession = factory.openSession(true);
import com.fox.dao.IUserDao;
import com.fox.pojo.User;
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.Test;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest {
private InputStream in = null;
private SqlSession sqlSession =null;
private IUserDao userDao = null;
@Before //标记在非静态方法上。在@Test方法前面执行,而且是在每一个@Test方法前面都执行。
public void init() throws IOException {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.使用构建者创建工厂对象 SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.使用 SqlSessionFactory 生产 SqlSession 对象
sqlSession = factory.openSession(true);
//4.使用 SqlSession 创建 dao 接口的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After //标记在非静态方法上。在@Test方法后面执行,而且是在每一个@Test方法后面都执行。
public void destroy() throws IOException {
//释放资源
sqlSession.close();
in.close();
}
@Test
public void testAddUser(){
User user = new User();
//由于id是自增的,所以没有id
user.setUserName("小黑");
user.setBirthday(new Date());
user.setUserAddress("上海");
user.setSex("男");
userDao.addUser(user);
}
}
所对应的 DefaultSqlSessionFactory 类的源代码:
运行的结果如下:
我们发现,此时事务就设置为自动提交了,同样可以实现CUD操作时记录的保存。虽然这也是一种方式,但就编程而言,设置为自动提交方式为 false 再根据情况决定是否进行提交,(手动提交事务)这种方式更常用。因为我们可以根据业务情况来决定提交是否进行提交。
Mybatis 的映射文件中,前面我们的 SQL 都是比较简单的,有些时候业务逻辑复杂时,我们的 SQL 是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了。
标签我们根据实体类的不同取值,使用不同的 SQL 语句来进行查询。比如在 id 如果不为空时可以根据 id 查询,如果 username 不为空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。
案例:
数据库:
对应的实体类User(字段与列名故意不一致):
import java.util.Date;
public class User{
private Integer id;
private String userName;
private Date birthday;
private String sex;
private String userAddress;
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", userAddress='" + userAddress + '\'' +
'}';
}
}
IUserDao:
import com.fox.pojo.User;
import java.util.List;
public interface IUserDao {
List<User> findByUser(User user);
}
IUserDao.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fox.dao.IUserDao">
<resultMap id="userMap" type="com.fox.pojo.User">
<id column="id" property="id"/>
<result column="username" property="userName"/>
<result column="sex" property="sex"/>
<result column="address" property="userAddress"/>
<result column="birthday" property="birthday"/>
resultMap>
<select id="findByUser" parameterType="com.fox.pojo.User" resultMap="userMap">
select * from user where 1=1
<if test="userName!=null and userName!=''">
and username = #{userName}
if>
<if test="userAddress!=null">
and address=#{userAddress}
if>
select>
mapper>
测试类:
import com.fox.dao.IUserDao;
import com.fox.pojo.User;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
private InputStream in = null;
private SqlSession sqlSession =null;
private IUserDao userDao = null;
@Before //标记在非静态方法上。在@Test方法前面执行,而且是在每一个@Test方法前面都执行。
public void init() throws IOException {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.使用构建者创建工厂对象 SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.使用 SqlSessionFactory 生产 SqlSession 对象
sqlSession = factory.openSession();
//4.使用 SqlSession 创建 dao 接口的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After //标记在非静态方法上。在@Test方法后面执行,而且是在每一个@Test方法后面都执行。
public void destroy() throws IOException {
sqlSession.commit();
//释放资源
sqlSession.close();
in.close();
}
@Test
public void testFindByUser(){
User user = new User();
user.setUserName("小明");
user.setUserAddress("广东");
List<User> list = userDao.findByUser(user);
for (User user1 : list) {
System.out.println(user1);
}
}
}
标签为了简化上面 where 1=1 的条件拼装,我们可以采用
标签来简化开发。
案例:
IUserDao:
import com.fox.pojo.User;
import java.util.List;
public interface IUserDao {
List<User> findByUser(User user);
}
IUserDao.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fox.dao.IUserDao">
<resultMap id="userMap" type="com.fox.pojo.User">
<id column="id" property="id"/>
<result column="username" property="userName"/>
<result column="sex" property="sex"/>
<result column="address" property="userAddress"/>
<result column="birthday" property="birthday"/>
resultMap>
<select id="findByUser" parameterType="com.fox.pojo.User" resultMap="userMap">
select * from user
<where>
<if test="userName!=null and userName!=''">
username = #{userName}
if>
<if test="userAddress!=null">
and address=#{userAddress}
if>
where>
select>
mapper>
测试类:
import com.fox.dao.IUserDao;
import com.fox.pojo.User;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
private InputStream in = null;
private SqlSession sqlSession =null;
private IUserDao userDao = null;
@Before //标记在非静态方法上。在@Test方法前面执行,而且是在每一个@Test方法前面都执行。
public void init() throws IOException {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.使用构建者创建工厂对象 SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.使用 SqlSessionFactory 生产 SqlSession 对象
sqlSession = factory.openSession();
//4.使用 SqlSession 创建 dao 接口的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After //标记在非静态方法上。在@Test方法后面执行,而且是在每一个@Test方法后面都执行。
public void destroy() throws IOException {
sqlSession.commit();
//释放资源
sqlSession.close();
in.close();
}
@Test
public void testFindByUser(){
User user = new User();
user.setUserName("小明");
user.setUserAddress("广东");
List<User> list = userDao.findByUser(user);
for (User user1 : list) {
System.out.println(user1);
}
}
}
标签假如我们需要传入多个 id 查询用户信息:
SELECT * FROM USERS WHERE id IN (42,43,46)
这样我们在进行范围查询时,就要将一个集合中的值,作为参数动态添加进来。
那么我们将如何进行参数的传递?这就要用到
标签
标签用于遍历集合,它的属性:
案例:
创建一个用于封装查询条件的类QueryVo,在 QueryVo 中加入一个 List 集合用于封装参数:
import java.io.Serializable;
import java.util.List;
public class QueryVo implements Serializable {
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
IUserDao:
import com.fox.pojo.User;
import java.util.List;
public interface IUserDao {
List<User> findInIds(QueryVo vo);
}
IUserDao.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fox.dao.IUserDao">
<resultMap id="userMap" type="com.fox.pojo.User">
<id column="id" property="id"/>
<result column="username" property="userName"/>
<result column="sex" property="sex"/>
<result column="address" property="userAddress"/>
<result column="birthday" property="birthday"/>
resultMap>
<select id="findInIds" parameterType="com.fox.pojo.QueryVo" resultMap="userMap">
select * from user
<where>
<if test="ids!=null and ids.size()>0">
<foreach collection="ids" open="id in (" close=")" item="uid" separator=",">
#{uid}
foreach>
if>
where>
select>
mapper>
测试类:
import com.fox.dao.IUserDao;
import com.fox.pojo.User;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
private InputStream in = null;
private SqlSession sqlSession =null;
private IUserDao userDao = null;
@Before //标记在非静态方法上。在@Test方法前面执行,而且是在每一个@Test方法前面都执行。
public void init() throws IOException {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.使用构建者创建工厂对象 SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.使用 SqlSessionFactory 生产 SqlSession 对象
sqlSession = factory.openSession();
//4.使用 SqlSession 创建 dao 接口的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After //标记在非静态方法上。在@Test方法后面执行,而且是在每一个@Test方法后面都执行。
public void destroy() throws IOException {
sqlSession.commit();
//释放资源
sqlSession.close();
in.close();
}
@Test
public void testFindInIds(){
QueryVo vo = new QueryVo();
List<Integer> list = new ArrayList<Integer>();
list.add(42);
list.add(43);
list.add(46);
vo.setIds(list);
List<User> users = userDao.findInIds(vo);
for (User user : users) {
System.out.println(user);
}
}
}
标签可将重复的 sql 语句提取出来,使用时用
标签引用即可,最终达到 sql 重用的目的。
案例:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fox.dao.IUserDao">
<resultMap id="userMap" type="com.fox.pojo.User">
<id column="id" property="id"/>
<result column="username" property="userName"/>
<result column="sex" property="sex"/>
<result column="address" property="userAddress"/>
<result column="birthday" property="birthday"/>
resultMap>
<sql id="defaultSql">
select * from user
sql>
<select id="findInIds" parameterType="com.fox.pojo.QueryVo" resultMap="userMap">
<include refid="defaultSql">include>
<where>
<if test="ids!=null and ids.size()>0">
<foreach collection="ids" open="id in (" close=")" item="uid" separator=",">
#{uid}
foreach>
if>
where>
select>
mapper>
表之间的关系有几种:
举例:
示例:用户和账户
一个账户只能属于一个用户(多个账户也可以属于同一个用户)
(1)建立两张表:用户表,账户表
让用户表和账户表之间具备一对多的关系,需要使用外键在账户表中添加:
user表:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(32) NOT NULL COMMENT '用户名称',
`birthday` DATETIME DEFAULT NULL COMMENT '生日',
`sex` CHAR(1) DEFAULT NULL COMMENT '性别',
`address` VARCHAR(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`username`,`birthday`,`sex`,`address`) VALUES (41,'老王','2018-02-27 17:47:08','男','北京'),(42,'小王','2018-03-02 15:09:37','女','安徽'),(43,'小二','2018-03-04 11:34:34','女','上海'),(45,'小明','2018-03-04 12:04:06','男','广东'),(46,'杰克','2018-03-07 17:37:26','男','北京'),(48,'小马','2018-03-08 11:44:00','女','北京');
account表:
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`ID` INT(11) NOT NULL COMMENT '编号',
`UID` INT(11) DEFAULT NULL COMMENT '用户编号',
`MONEY` DOUBLE DEFAULT NULL COMMENT '金额',
PRIMARY KEY (`ID`),
KEY `FK_Reference_8` (`UID`),
CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `account`(`ID`,`UID`,`MONEY`) VALUES (1,41,1000),(2,45,1000),(3,41,2000);
我们想要的结果:
当我们查询账户时,可以同时得到账户的所属用户信息
SELECT a.id AS aid,a.uid,a.money,u.* FROM account a,USER u WHERE a.uid=u.id;
(2)建立两个实体类:用户实体类和账户实体类
让账户和用户的实体类能体现出来一对一(多对一)的关系
User类:
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
Account类(一对一、多对一关系映射:从表实体应该包含一个主表实体的对象引用):
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//一对一关系映射:从表实体应该包含一个主表实体的对象引用
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}
(3)建立账户的配置文件
IAccountDao:
import com.fox.pojo.Account;
import java.util.List;
public interface IAccountDao {
//查询所有账户信息以及其所属的用户的信息
List<Account> findAll();
}
IAccountDao.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fox.dao.IAccountDao">
<resultMap id="accountUser" type="com.fox.pojo.Account">
<id property="id" column="aid">id>
<result property="uid" column="uid">result>
<result property="money" column="money">result>
<association property="user" column="uid" javaType="com.fox.pojo.User">
<id property="id" column="id">id>
<result property="username" column="username">result>
<result property="sex" column="sex">result>
<result property="address" column="address">result>
<result property="birthday" column="birthday">result>
association>
resultMap>
<select id="findAll" resultMap="accountUser">
select u.*,a.id as aid,a.uid,a.money from account a,user u where u.id = a.uid;
select>
mapper>
(4)测试类:
import com.fox.dao.IAccountDao;
import com.fox.pojo.Account;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class AccountTest {
private InputStream in = null;
private SqlSession sqlSession =null;
private IAccountDao accountDao = null;
@Before //标记在非静态方法上。在@Test方法前面执行,而且是在每一个@Test方法前面都执行。
public void init() throws IOException {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.使用构建者创建工厂对象 SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.使用 SqlSessionFactory 生产 SqlSession 对象
sqlSession = factory.openSession();
//4.使用 SqlSession 创建 dao 接口的代理对象
accountDao = sqlSession.getMapper(IAccountDao.class);
}
@After //标记在非静态方法上。在@Test方法后面执行,而且是在每一个@Test方法后面都执行。
public void destroy() throws IOException {
sqlSession.commit();
//释放资源
sqlSession.close();
in.close();
}
@Test
public void testFindAll(){
List<Account> accounts = accountDao.findAll();
for(Account account : accounts){
System.out.println("---------------每条账户信息--------------");
System.out.println(account);
System.out.println(account.getUser());
}
}
}
示例:用户和账户
一个用户可以有多个账户
(1)建立两张表:用户表,账户表。
两表同上例。
我们想要的结果:
当我们查询所有用户时,可以同时得到用户下所包含的账户信息(查询结果包含所有用户并不一定包含所有账户,因此用左外连接)
select u.*,a.id as aid,a.uid,a.money from user u left outer join account a on u.id=a.uid;
(2)建立两个实体类:用户实体类和账户实体类
让用户和账户的实体类能体现出来一对多的关系
Account类同上例。
User类(一对多关系映射:主表实体应该包含从表实体的集合引用):
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
//一对多关系映射:主表实体应该包含从表实体的集合引用
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
(3)建立用户的配置文件
IUserDao:
import com.fox.pojo.User;
import java.util.List;
//用户的持久层接口
public interface IUserDao {
//查询所有用户信息以及其帐户信息
List<User> findAll();
}
IUserDao.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fox.dao.IUserDao">
<resultMap id="userAccount" type="com.fox.pojo.User">
<id property="id" column="id">id>
<result property="username" column="username">result>
<result property="birthday" column="birthday">result>
<result property="sex" column="sex">result>
<result property="address" column="address">result>
<collection property="accounts" ofType="com.fox.pojo.Account">
<id property="id" column="aid">id>
<result property="uid" column="uid">result>
<result property="money" column="money">result>
collection>
resultMap>
<select id="findAll" resultMap="userAccount">
select u.*,a.id as aid,a.uid,a.money from user u left outer join account a on u.id=a.uid;
select>
mapper>
(4)测试类:
import com.fox.dao.IUserDao;
import com.fox.pojo.User;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class UserTest {
private InputStream in = null;
private SqlSession sqlSession =null;
private IUserDao userDao = null;
@Before //标记在非静态方法上。在@Test方法前面执行,而且是在每一个@Test方法前面都执行。
public void init() throws IOException {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.使用构建者创建工厂对象 SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.使用 SqlSessionFactory 生产 SqlSession 对象
sqlSession = factory.openSession();
//4.使用 SqlSession 创建 dao 接口的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After //标记在非静态方法上。在@Test方法后面执行,而且是在每一个@Test方法后面都执行。
public void destroy() throws IOException {
sqlSession.commit();
//释放资源
sqlSession.close();
in.close();
}
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println("----------用户信息----------");
System.out.println(user);
System.out.println(user.getAccounts());
}
}
}
多对多关系其实我们可以看成是双向的一对多关系。
示例:用户和角色
一个用户可以有多个角色
一个角色可以赋予多个用户
(1)建立三张表:用户表,角色表,中间表
让用户表和角色表具有多对多的关系。需要使用中间表,中间表中包含用户表和角色表各自的主键,在中间表中是外键。
用户表同上例。
角色表:
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` INT(11) NOT NULL COMMENT '编号',
`role_name` VARCHAR(30) DEFAULT NULL COMMENT '角色名称',
`role_desc` VARCHAR(60) DEFAULT NULL COMMENT '角色描述',
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `role`(`id`,`role_name`,`role_desc`) VALUES (1,'院长','管理整个学院'),(2,'总裁','管理整个公司'),(3,'校长','管理整个学校');
中间表:
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`uid` INT(11) NOT NULL COMMENT '用户编号',
`rid` INT(11) NOT NULL COMMENT '角色编号',
PRIMARY KEY (`uid`,`rid`),
KEY `FK_Reference_10` (`rid`),
CONSTRAINT `FK_Reference_10` FOREIGN KEY (`rid`) REFERENCES `role` (`id`),
CONSTRAINT `FK_Reference_9` FOREIGN KEY (`uid`) REFERENCES `user` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user_role`(`uid`,`rid`) VALUES (41,1),(45,1),(41,2);
(2)建立两个实体类:用户实体类和角色实体类
让用户和角色的实体类能体现出来多对多的关系,各自包含对方一个集合引用。
User:
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
//多对多的关系映射:各自包含对方一个集合引用(一个用户可以具备多个角色)
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
Role:
import java.io.Serializable;
import java.util.List;
public class Role implements Serializable {
private Integer roleId;
private String roleName;
private String roleDesc;
//多对多的关系映射:各自包含对方一个集合引用(一个角色可以赋予多个用户)
private List<User> users;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
@Override
public String toString() {
return "Role{" +
"roleId=" + roleId +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
(3)建立配置文件
用户的配置文件
IUserDao:
import com.fox.pojo.User;
import java.util.List;
public interface IUserDao {
//查询所有用户以及所包含的角色信息
List<User> findAll();
}
IUserDao.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fox.dao.IUserDao">
<resultMap id="userMap" type="com.fox.pojo.User">
<id property="id" column="id">id>
<result property="username" column="username">result>
<result property="birthday" column="birthday">result>
<result property="sex" column="sex">result>
<result property="address" column="address">result>
<collection property="roles" ofType="role">
<id property="roleId" column="rid">id>
<result property="roleName" column="role_name">result>
<result property="roleDesc" column="role_desc">result>
collection>
resultMap>
<select id="findAll" resultMap="userMap">
select r.id as rid,r.role_name,r.role_desc,u.* from user u
left outer join user_role ur on u.id=ur.uid
left outer join role r on ur.rid=r.id
select>
mapper>
角色的配置文件
IRoleDao:
import com.fox.pojo.Role;
import java.util.List;
public interface IRoleDao {
//查询所有角色信息以及所对应的用户信息
List<Role> findAll();
}
IRoleDao.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fox.dao.IRoleDao">
<resultMap id="roleMap" type="com.fox.pojo.Role">
<id property="roleId" column="rid">id>
<result property="roleName" column="role_name">result>
<result property="roleDesc" column="role_desc">result>
<collection property="users" ofType="com.fox.pojo.User">
<id property="id" column="id">id>
<result property="username" column="username">result>
<result property="sex" column="sex">result>
<result property="birthday" column="birthday">result>
<result property="address" column="address">result>
collection>
resultMap>
<select id="findAll" resultMap="roleMap">
select r.id as rid,r.role_name,r.role_desc,u.* from role r
left outer join user_role ur on r.id=ur.rid
left outer join user u on ur.uid=u.id;
select>
mapper>
(4)测试:
当我们查询所有用户时,可以同时得到用户所包含的角色信息:
import com.fox.dao.IUserDao;
import com.fox.pojo.User;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class UserTest {
private InputStream in = null;
private SqlSession sqlSession =null;
private IUserDao userDao = null;
@Before //标记在非静态方法上。在@Test方法前面执行,而且是在每一个@Test方法前面都执行。
public void init() throws IOException {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.使用构建者创建工厂对象 SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.使用 SqlSessionFactory 生产 SqlSession 对象
sqlSession = factory.openSession();
//4.使用 SqlSession 创建 dao 接口的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After //标记在非静态方法上。在@Test方法后面执行,而且是在每一个@Test方法后面都执行。
public void destroy() throws IOException {
sqlSession.commit();
//释放资源
sqlSession.close();
in.close();
}
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println("----------每个用户信息----------");
System.out.println(user);
System.out.println(user.getRoles());
}
}
}
import com.fox.dao.IRoleDao;
import com.fox.pojo.Role;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class RoleTest {
private InputStream in = null;
private SqlSession sqlSession =null;
private IRoleDao roleDao = null;
@Before //标记在非静态方法上。在@Test方法前面执行,而且是在每一个@Test方法前面都执行。
public void init() throws IOException {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.使用构建者创建工厂对象 SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.使用 SqlSessionFactory 生产 SqlSession 对象
sqlSession = factory.openSession();
//4.使用 SqlSession 创建 dao 接口的代理对象
roleDao = sqlSession.getMapper(IRoleDao.class);
}
@After //标记在非静态方法上。在@Test方法后面执行,而且是在每一个@Test方法后面都执行。
public void destroy() throws IOException {
sqlSession.commit();
//释放资源
sqlSession.close();
in.close();
}
@Test
public void testFindAll(){
List<Role> roles = roleDao.findAll();
for (Role role : roles) {
System.out.println("---------每个角色信息----------");
System.out.println(role);
System.out.println(role.getUsers());
}
}
}