mybatis中的连接池
mybatis连接池提供了3种方式的配置:
配置的位置:
主配置文件SqlMapConfig.xml中的dataSource标签,type属性就是表示采用何种连接池方式。
type属性的取值:
POOLED: 采用传统的 javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现
UNPOOLED: 采用传统的获取连接的方式,虽然也实现了javax.sql.DataSource接口,但
是,但是并没有使用池的思想
JNDI: 采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到的
DataSource是不一样的注意:如果不是web或者maven的war工程,是不能使用的。
POOLED
UNPOOLED
JNDI(模拟windows注册表)
实现步骤:
1.创建web工程
2.导入依赖jjar
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
3.在webapp目录下创建META-INF目录
4.在META-INF目录下创建xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!--
<Resource
name="jdbc/eesy_mybatis" 数据源的名称
type="javax.sql.DataSource" 数据源类型
auth="Container" 数据源提供者
maxActive="20" 最大活动数
maxWait="10000" 最大等待时间
maxIdle="5" 最大空闲数
username="root" 用户名
password="1234" 密码
driverClassName="com.mysql.jdbc.Driver" 驱动类
url="jdbc://localhost:3306/eesy" 连接url字符串
/>
-->
<Resource
name="jdbc/eesy_mybatis"
type="javax.sql.DataSource"
auth="Container"
maxActive="20"
maxWait="10000"
maxIdle="5"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc://localhost:3306/eesy"
/>
</Context>
5.不需要使用引用外部数据源
6.总结:
测试类直接运行会报错,因为测试类是一个java程序,不经过服务器tomcat,拿不到JDNI配置的数据源。如果将代码copy到jsp文件中,则可以成功运行,因为jsp运行借助服务器tomcat,tomcat利用JNDI技术拿到数据源,供jsp代码使用。
mybatis中的事务
在创建SqlSession的时候传入true来开启事务自动提交
设置完自动提交后,不再出现关闭自动提交然后又打开的日志信息
动态sql
<!--根据条件查询-->
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user where 1=1
<if test="username !=null">
and username = #{username}
</if>
<if test="sex!=null">
and sex=#{sex}
</if>
</select>
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user
<where>
<if test="username !=null">
and username = #{username}
</if>
<if test="sex!=null">
and sex=#{sex}
</if>
</where>
</select>
<!--根据QueryVo中的id集合实现查询用户列表-->
<select id="findUserInIds" resultMap="userMap" parameterType="QueryVo">
select * from user
<where>
<if test="ids!=null and ids.size()>0">
<foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
foreach结果
多表查询
表之间的关系有几种:
一对多
多对一
一对一
多对多
举例:
用户和订单就是一对多
订单和用户就是多对一
一个用户可以下多个订单
多个订单属于同一个用户
人和身份证就是一对一
一个人只能有一个身份证号
一个身份证只属于一个人
老师和学生之间是多对多
一个学生可以被多个老师教过
一个老师可以教过多个学生
特例:
如果拿出每一个订单,他都只能属于一个用户
所以mybatis就把多对一看成一对一
mybatis中的多表查询:
一对多
示例:用户和账户
一个用户可以有多个账户
一个账户只能属于一个用户(多个账户也可以属于同一个用户)
步骤:
1.建立两张表:用户表,账户表
让用户表和账户表之间具备一对多的关系:需要使用外键再账户表中添加
2.建立两个实体类:用户实体类和账户实体类
让用户和账户的实体类能体现出一对多的关系
3.建立两个配置文件
用户的配置文件
账户的配置文件
4.实现配置:
当我们查询用户时,可以同时得到用户下所包含的账户信息
当我们查询账户时,可以同时得到账户信息的所属用户信息
一、建立两张表,在多的一方建立外键指向一的一方来实现一对多
二、 建立两个实体类,
1.账户实体类,添加对用户实体的引用,实现一对一
package com.tiger.domain;
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 +
'}';
}
}
2.用户实体类,添加对账户实体类的集合引用,实现一对多
package com.tiger.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
//一对多关系映射,主表实体应该包含从表实体的集合引用
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
三、建立两个配置文件
1.账户配置文件
<?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.tiger.dao.AccountDao">
<!--定义封装account和user的resultMap-->
<resultMap id="accountUserMap" type="account">
<id property="id" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!--一对一的关系映射,配置封装user的内容-->
<association property="user" column="uid" javaType="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
</association>
</resultMap>
<!--查询所有-->
<select id="findAll" resultMap="accountUserMap">
select u.*,a.id as aid,a.uid,a.money from account a,user u where u.id=a.uid;
</select>
</mapper>
2.用户配置文件
<?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.tiger.dao.UserDao">
<!--定义user的resultMap-->
<resultMap id="userAccountMap" type="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>
<!--配置user对象中accounts集合的映射-->
<collection property="accounts" ofType="account">
<id property="id" column="aid"></id>
<result property="money" column="money"></result>
<result property="uid" column="uid"></result>
</collection>
</resultMap>
<!--查询所有-->
<select id="findAll" resultMap="userAccountMap">
select * from user u left outer join account a on u.id=a.uid;
</select>
</mapper>
四、对应sql
<!--查询所有-->
<select id="findAll" resultMap="accountUserMap">
select u.*,a.id as aid,a.uid,a.money from account a,user u where u.id=a.uid;
</select>
<!--查询所有-->
<select id="findAll" resultMap="userAccountMap">
select * from user u left outer join account a on u.id=a.uid;
</select>
多对多
示例:用户和角色
一个用户可以有多个角色
一个角色可以赋予多个用户
步骤:
1.建立两张表:用户表,角色表
让用户表和角色表之间具备多对多的关系:需要使用中间表,中间表包含各自的
主键,在中间表中是外键
2.建立两个实体类:用户实体类和角色实体类
让用户实体和角色的实体类能体现出多对多的关系,各自包含对方集合引用
3.建立两个配置文件
用户的配置文件
角色的配置文件
4.实现配置:
当我们查询用户时,可以同时得到用户下所包含的角色信息
当我们查询角色时,可以同时得到角色的所赋予的用户信息
一、建立三张表
用user_role作为user表和role表的中间表
二、创建两个实体类
1.用户实体类,添加对角色集合的引用
package com.tiger.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
//多对多的关系映射:一个用户可以具备多个角色
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
2.角色实体类,添加对用户实体类集合的引用
package com.tiger.domain;
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 + '\'' +
'}';
}
}
三、建立两个配置文件
1.用户配置文件
<?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.tiger.dao.UserDao">
<!--定义user的resultMap-->
<resultMap id="userMap" type="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 u.*,r.id as rid ,r.role_name,r.role_desc from user u
left outer join user_role ur on u.id=ur.uid
left outer join role r on r.id=ur.rid
</select>
</mapper>
2.角色配置文件
<?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.tiger.dao.RoleDao">
<!--定义role表的resultMap-->
<resultMap id="roleMap" type="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="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>
</resultMap>
<!--查询所有-->
<select id="findAll" resultMap="roleMap">
select u.*,r.id as rid ,r.role_name,r.role_desc from role r
left outer join user_role ur on r.id=ur.rid
left outer join user u on u.id=ur.uid;
</select>
</mapper>
mybatis中的延迟加载
问题:在一对多中,当我们有一个用户,它有100个账户。
在查询用户的时候,要不要把关联的账户查出来?
在查询账户时,要不要把关联的用户查询出来?
在查询用户时,用户下的账户信息应该是,什么时候使用什么时候查询的。
在查询账户信息时,账户的所属用户信息应该是随着账户查询时一起查询出来的。
什么是延迟加载:
在真正使用数据的时候才发起查询,不用的时候不查询。按需加载(懒加载)
什么是立即加载
不管用不用,只要一调用方法,马上发起查询
在对应的四种表关系中:一对多,多对一,一对一,多对多
一对多,多对多:通常情况下采用延迟加载。
多对一,一对一:通常情况下采用立即加载。
步骤:
1.在主配置文件中开启mybatis延迟加载
2.修改resultMap
<!--定义user的resultMap-->
<resultMap id="userAccountMap" type="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>
<!--配置user对象中accounts集合的映射-->
<collection property="accounts" ofType="account" select="com.tiger.dao.AccountDao.findAccountByUid" column="id"></collection>
</resultMap>
<!--定义封装account和user的resultMap-->
<resultMap id="accountUserMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!--一对一的关系映射,配置封装user的内容
select里面指定的内容:查询用户的唯一标识:
column属性指定的内容:用户根据id查询时,所需要的参数值
-->
<association property="user" column="uid" javaType="user" select="com.tiger.dao.UserDao.findById"></association>
</resultMap>
3.结果:
当不调用对应方法时,就不会加载
当调用对应方法时,就会加载
mybatis中的缓存
什么是缓存
存在于内存中的临时数据。
为什么使用缓存
减少和数据库的交互次数,提高执行效率
什么样的数据能使用缓存,什么样的数据不能使用缓存
适用于缓存:
经常查询并且不经常改变的。
数据的正确与否对最终结果影响不大的
不适用于缓存:
经常改变的数据
数据的正确与否对最终结果影响很大的。
例如:商品的库存,银行的汇率,股市的牌价。
mybatis中的一级缓存和二级缓存
一级缓存:指的是mybatis中SqlSession对象的缓存。
当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供的一块区域中
该区域的结构是一个map。当我们再次查询,同样的数据,mybatis会先去sqlSession中
查看是否有,有的话直接拿出来用。
当SqlSession对象消失时,mybatis的一级缓存也就消失了
一级缓存的分析:
一级缓存是sqlsession范围内的缓存,当调用sqlsession的修改,添加,删除, commit(),close()等方法时,就会清空一级缓存。
二级缓存:它指的是mybatis中SqlSessionFactory对
象的缓存。由同一个SqlSessionFactory对象创建的SqlSession,共享其缓存。
二级缓存的使用步骤:
第一步:让mybatis支持二级缓存(在主配置文件SqlMapConfig.xml中配置)
第二步:让当前的映射文件支持二级缓存(在UserDao.xml中配置)
第三步:让当前的操作支持二级缓存(在select标签中配置)
一级缓存
一、当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供的一块区域中,该区域的结构是一个map。当我们再次查询,同样的数据,mybatis会先去sqlSession中查看是否有,有的话直接拿出来用。
/**
* 测试一级缓存
*/
@Test
public void testFirstLevelCache1(){
User user1 =userDao.findById(1);
System.out.println(user1);
User user2 = this.userDao.findById(1);
System.out.println(user2);
System.out.println(user1==user2);
}
控制台输出
调用两次,但是只查询一次数据库
二、 当SqlSession对象消失时,mybatis的一级缓存也就消失了
/**
* 测试一级缓存
*/
@Test
public void testFirstLevelCache(){
User user1 =userDao.findById(1);
System.out.println(user1);
//关闭sqlsession
sqlSession.close();
//再次获取sqlsession对象
sqlSession=factory.openSession(true);
userDao = sqlSession.getMapper(UserDao.class);
User user2 = this.userDao.findById(1);
System.out.println(user2);
System.out.println(user1==user2);
}
控制台输出
调用两次查询两次数据库
另一种清空方式清空缓存
/**
* 测试一级缓存
*/
@Test
public void testFirstLevelCache(){
User user1 =userDao.findById(1);
System.out.println(user1);
//此方法也可以清空缓存
sqlSession.clearCache();
User user2 = this.userDao.findById(1);
System.out.println(user2);
System.out.println(user1==user2);
}
控制台输出
调用两次sql语句
三、当调用sqlsession的修改,添加,删除, commit(),close()等方法时,就会清空一级缓存。
/**
* 测试缓存的同步
*/
@Test
public void testClearCache(){
//1.根据id查询用户
User user1 =userDao.findById(1);
System.out.println(user1);
//2.更新用户信息
user1.setUsername("update user clear cache");
user1.setAddress("陕西西安");
userDao.updateUser(user1);
//3.再次查询id为1的用户
User user2 = this.userDao.findById(1);
System.out.println(user2);
System.out.println(user1==user2);
}
控制台输出
执行两次sql
二级缓存
@Test
public void testFirstLevelCache(){
SqlSession sqlSession1 = factory.openSession();
UserDao dao1 = sqlSession1.getMapper(UserDao.class);
User user1 =dao1.findById(1);
System.out.println(user1);
sqlSession1.close();//一级缓存消失
SqlSession sqlSession2 = factory.openSession();
UserDao dao2 = sqlSession2.getMapper(UserDao.class);
User user2 =dao2.findById(1);
System.out.println(user2);
sqlSession2.close();
System.out.println(user1==user2);
}
1.在主配置文件开启二级缓存
在mapper中和select标签中开启二级缓存
控制台输出,因为二级缓存中存储的数据,而不是对象,所以每次需要,都会创建新的对象对数据封装,所以两个地址User不同
查询一次sql