mybatis基础讲解:
mybatis(一)数据库事务与环境搭建
mybatis(二)mybatis的执行流程
mybatis(三)动态sql与多表查询
mybatis(四)多参传递、延时加载、缓存及注解开发
一、数据库事务
-
数据库事务:
一件完整的事情, 要么全部成功,要么就全部失败 -
如何开启事务:
Start transaction;
之前的转账操作(如果在转账过程中出现异常:rollback)
Commit;提交 -
事务的特性(ACID):
原子性:atomicity 要么全部成功 要么全部失败 不可以分割
一致性: consistency 事务前后,所有的状态都要保持一致
隔离性:Isolation 一个事务最好不要受到其他事务的影响
持久性:durability 将提交或者回滚的事务 存储到数据库中 -
不考虑隔离性,导致的问题
脏读:读取到另一个事务中未提交的数据
不可重复读:在同一个事务中,两次查询结果不一样(update)
虚读(幻读):在同一个事务中,两次查询结果不一样(insert) -
隔离级别
read uncommitted : 读取尚未提交的数据 :哪个问题都不能解决
read committed:读取已经提交的数据 :可以解决脏读 ---- oracle默认
repeatable read:重读读取:可以解决脏读 和 不可重复读 —mysql默认的
serializable:串行化:可以解决 脏读 不可重复读 和 虚读—相当于锁表
查看数据库的隔离级别:
Select @@tx_isolation;
Mysql 默认的隔离级别:repeatable-read;
Oracle : read committed
设置mysql的隔离级别:set session transaction isolation level 设置事务隔离级别
二、与IDEA环境的搭建
- 创建maven工程,配置pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.xmcc</groupId>
<artifactId>mybatisdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
-
创建实体类(与数据库表格对应)
-
dao接口(提供方法)
package com.xmcc.dao;
import com.xmcc.entity.Account;
import com.xmcc.entity.AccountUser;
import com.xmcc.entity.QueryVo;
import com.xmcc.entity.User;
import java.util.List;
public interface UserDao {
// @Select("select * from user")
List<User> findAll();
void update(User user);
User findOnById(QueryVo vo);
//添加
void save(User user);
//删除
void delete(int id);
//通过姓名查找
List<User> findUserByName(String name);
//查询总条数
int findTotal();
//条件查询
List<User> findUserByCondition(User user);
List<User> findUserByQuery(QueryVo vo);
//查询账户以及账户对应的用户信息
//方式一:继承
List<AccountUser> findAccountUser();
//方式2:resultMap
List<Account> findAccount();
//查询用户 以及用户对应的账户信息
List<User> findUser();
//查询用户信息以及用户对应的角色信息
List<User> findUserRole();
//查询角色以及角色对应的用户信息
}
- mybatis的配置文件:SqlMapConfig.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="jdbcConfig.properties"></properties>
<typeAliases>
<!-- 定义单个别名 -->
<!--<typeAlias type="com.xmcc.entity.User" alias="user"></typeAlias>-->
<!-- 批量定义别名 -->
<package name="com.xmcc.entity"></package>
</typeAliases>
<!-- 配置mybatis环境 -->
<environments default="devlopment">
<environment id="devlopment">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<!--没有jdbcConfig.properties文件时:-->
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisdb"></property>
<property name="username" value="root"></property>
<property name="password" value="1"></property>
<!--有jdbcConfig.properties文件时:-->
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<!-- 引入映射配置文件 -->
<mappers>
<!-- xml -->
<!--<mapper resource="com/xmcc/dao/UserDao.xml"></mapper>-->
<!-- 注解 -->
<!--<mapper class="com.xmcc.dao.UserDao"></mapper>-->
<!-- 批量引入映射文件 -->
<package name="com.xmcc.dao"></package>
</mappers>
</configuration>
5.对象映射文件:xxxDao.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">
<!-- namespace:就是 接口的全路径名 -->
<mapper namespace="com.xmcc.dao.UserDao">
<resultMap id="userMap" type="com.xmcc.entity.User">
<!--主键-->
<id column="id" property="userId"></id>
<result column="username" property="userName"></result>
<result column="birthday" property="userBirthday"></result>
<result column="sex" property="userSex"></result>
<result column="address" property="userAddress"></result>
</resultMap>
<resultMap id="userMap1" type="com.xmcc.entity.User">
<!--主键-->
<id column="id" property="id"></id>
<result column="username" property="username"></result>
<result column="birthday" property="birthday"></result>
<result column="sex" property="sex"></result>
<result column="address" property="address"></result>
<collection property="accounts" ofType="account">
<id column="aid" property="id"></id>
<result column="uid" property="uid"></result>
<result column="money" property="money"></result>
</collection>
</resultMap>
<resultMap id="accountMap" type="account">
<id column="id" property="id"></id>
<result column="uid" property="uid"></result>
<result column="money" property="money"></result>
<association property="user" javaType="user" >
<id column="uid" property="id"></id>
<result column="username" property="username"></result>
<result column="birthday" property="birthday"></result>
<result column="sex" property="sex"></result>
<result column="address" property="address"></result>
</association>
</resultMap>
<resultMap id="userrole" type="user">
<!--主键-->
<id column="id" property="id"></id>
<result column="username" property="username"></result>
<result column="birthday" property="birthday"></result>
<result column="sex" property="sex"></result>
<result column="address" property="address"></result>
<collection property="roles" ofType="role">
<id column="rid" property="roleId"></id>
<result column="role_name" property="roleName"></result>
<result column="role_desc" property="roleDesc"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="userMap">
select * from user;
</select>
<!-- #{}:占位符 等同于 ? -->
<!-- 如果是普通 可以随便写什么 但是最好保持一致 -->
<select id="findOnById" resultType="user" parameterType="com.xmcc.entity.QueryVo">
select * from user where id = #{user.id};
</select>
<!-- 如果parameterType是对象 那么 需要使用对象中的javabe属性
(ognl语法:#{对象[.对象].javabean属性}) -->
<update id="update" parameterType="User">
update user set sex = #{sex} where id = #{id};
</update>
<insert id="save" parameterType="User">
<!-- 在添加user以后 将我们的 id值 也封装到 User对象中 -->
<selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
select last_insert_id()
</selectKey>
insert into user (username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
</insert>
<delete id="delete" parameterType="int">
delete from user where id = #{id}
</delete>
<!-- ${}:如果传入的是基本数据类型 那么里面都是value -->
<select id="findUserByName" parameterType="string" resultType="User">
select * from user where username like #{name}
</select>
<select id="findTotal" resultType="int">
select count(id) from user;
</select>
<sql id="select">
select * from user
</sql>
<select id="findUserByCondition" resultType="user" parameterType="user">
<include refid="select"></include>
<where>
<if test="username != null and username != ''">
and username like #{username}
</if>
<if test="address != null and address != ''">
and address like #{address}
</if>
</where>
</select>
<select id="findUserByQuery" parameterType="queryvo" resultType="user">
select * from user
<where> <!-- select * from user where (id in( ,,,,))-->
<!--
collection:目标遍历容器
item:遍历出来后的对象
open:从什么开始
close:以什么结束
separator:分割符
-->
<if test="ids.size() > 0">
<foreach collection="ids" item="id" open="id in (" close=")" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
<!-- 继承方式 -->
<select id="findAccountUser" resultType="accountuser">
select account.*,user.username,user.address from account,user where account.UID = user.id
</select>
<!-- resultMap -->
<select id="findAccount" resultMap="accountMap">
select account.*,user.id uid,user.username,user.address from account,user where account.UID = user.id
</select>
<select id="findUser" resultMap="userMap1">
select user.*,account.id aid, account.uid ,account.money from user left join account on user.id = account.UID
</select>
<select id="findUserRole" resultMap="userrole">
select user.*,role.id rid,role.role_name,role.role_desc
from user left join user_role on user.id = user_role.UID left join role on user_role.RID = role.ID
</select>
</mapper>
环境搭建注意点:
1、xxxDao.xml 和 xxxDao.java 名字和路径需要保持一致
2、映射配置文件的的mapper标签中的 namespace的属性取值必须是dao接口的全限定名
3、映射配置文件的操作配置(select) ,id属性的取值必须是dao接口中的方法名