Mybatis
一、内容介绍
-
框架的介绍
-
介绍mybatis框架
-
JDBC于Mybatis框架的比较
-
自定义Mybatis框架
-
mybatis框架的快速入门
二、框架的介绍
1、什么是框架
1. 半成品,
2. 饭店:买菜,油盐酱醋-- 洗菜 -- 炒菜--做饭 -- 刷锅,洗碗
2、框架能解决什么问题
1、把技术封装起来
2、在开发中不应该考虑技术, 专注于逻辑(业务)开发
3, 框架时位于底层技术 和应用程序之间的代码
3、三层架构中常用的框架
a、web:表现层: 处理用户请求和响应
servlet -- struts(放弃) -- struts2(放弃) -- springMVC(主流)
b、service:业务层
自己写业务 --- ejb -- spring(整合框架,业务)(不可取代)
c、dao: 持久层(数据接收对象)
jdbc--dbutils--BeanUtils -- jdbcTemplate -- hibernate(放弃)--mybatis(主流)--spring data jpa(趋势)
主流:整合: springmvc + spring + mybatis = ssm
趋势:整合:springmvc + spring +spring data = spring全家桶
三、mybatis框架的介绍
了解Mybatis
MyBatis是一款优秀的持久层框架,它可以与Java程序无缝集成,提供了一种简单而灵活的方式来访问数据库。本文将介绍MyBatis的基本概念、使用方法和一些最佳实践。
一、MyBatis基本概念
- Mapper:MyBatis中的映射器(Mapper)是接口,用于定义SQL语句的映射关系。它通常包含一组方法,每个方法对应一个SQL语句,这些方法的参数类型应该与SQL语句中的参数类型相对应。
- XML文件:MyBatis使用XML文件作为配置文件,其中包含了所有的映射器接口和SQL语句。在XML文件中,可以使用标签定义SQL语句的格式、参数类型、返回值类型等信息。
- SqlSessionFactory:SqlSessionFactory是MyBatis的核心组件之一,它负责创建SqlSession对象,并提供给应用程序使用。SqlSessionFactory可以通过读取XML文件或者注解来创建SqlSession对象。
二、MyBatis使用方法
- 配置MyBatis环境:在使用MyBatis之前,需要先配置MyBatis的环境。这包括设置数据源、注册映射器接口和加载XML文件等操作。
- 编写映射器接口:根据业务需求,编写相应的映射器接口,并在其中定义SQL语句。
- 编写XML文件:在XML文件中定义SQL语句的格式、参数类型、返回值类型等信息。
- 注册映射器接口:将编写好的映射器接口注册到SqlSessionFactory中。
- 获取SqlSession对象:通过SqlSessionFactory获取SqlSession对象,然后使用该对象执行SQL语句。
三、MyBatis最佳实践
- 避免硬编码:尽量避免在代码中直接写SQL语句,而是使用映射器接口来定义SQL语句。这样可以提高代码的可维护性和可扩展性。
- 使用动态SQL:如果需要根据不同的条件来执行不同的SQL语句,可以使用动态SQL来实现。动态SQL可以根据条件生成不同的SQL语句,从而提高了代码的灵活性和可重用性。
- 缓存机制:为了提高查询效率,可以使用缓存机制来缓存查询结果。MyBatis提供了一级缓存和二级缓存两种缓存机制,可以根据实际情况选择合适的缓存机制。
总之,MyBatis是一款非常优秀的持久层框架,它可以帮助开发人员轻松地访问数据库,并提供了灵活的配置方式和丰富的功能支持。通过掌握MyBatis的基本概念、使用方法和最佳实践,可以更好地利用MyBatis来开发高质量的Java应用程序。
1、jdbc中的代码
package com.itheima;
import com.itheima.domain.User;
import org.junit.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* 回顾jdbc代码
*/
public class TestJDBC {
@Test
public void test(){
List<User> userList = new ArrayList<>();
//1. 注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/mybatisdb_331";
String username = "root";
String password = "root";
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
//2. 获取连接
conn = DriverManager.getConnection(url, username ,password);
// 3. SQL语句
String sql = "select * from user";
//4. 创建statement对象: Statement , PreparedStatement
pst = conn.prepareStatement(sql);
//5. 执行SQL语句,返回结果集
rs = pst.executeQuery();
//6. 处理结果集
while(rs.next()){//判断是否有下一条记录,如果有,说明有一个User对象
User user = new User();
//获取ResultSet中的值,赋值给user对象
int id = rs.getInt("id");
user.setId(id);
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setSex(rs.getString("sex"));
user.setAddress(rs.getString("address"));
//添加到集合中
userList.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7. 释放资源: 先开后关
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst != null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//打印结果
for (User user : userList) {
System.out.println(user);
}
}
}
2、jdbc代码中的问题
a、频繁创建和释放数据库的连接对象,造成资源的浪费. 使用数据库连接池可以解决(c3p0 ,dbcp, spring jdbc ,durid)
b、sql语句硬编码(写死),如果数据库发生改变,需要重新编译代码,再运行 。 可以考虑把sql语句写到配置文件中
c、传参数硬编码,必须按照特定的顺序传参
d、处理结果集硬编码,如果改变了数据库,结果集的映射必须重新写,需要重新编译代码,再运行
e、连接的配置信息硬编码
3、mybatis框架的概述
四、Mybatis框架的快速入门
1、添加依赖(jar)
<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.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
2、编写pojo对象
package com.itheima.domain;
/**
* 包装类型: 初始值为null
* 基本数据类型:本身的值就是一个状态
*
*/
public class User {
private Integer id;
private String username;
private String password;
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 + '\'' +
", password='" + password + '\'' +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
3、编写映射文件
<?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.itheima.dao.UserDao">
<select id="findAll" resultType="com.itheima.domain.User">
select * from user
</select>
</mapper>
4、编写核心配置文件
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatisdb_331?characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!--关联映射文件-->
<mappers>
<mapper resource="com/itheima/mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
5、测试框架
package com.itheima;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
public class TestCustomFrame {
@Test
public void test(){
//获取配置文件的输入流对象
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//创建SqlSessionFactory对象
SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//获取sqlSession对象
SqlSession sqlSession = sessionFactory.openSession();
//执行sql语句
List list = sqlSession.selectList("com.itheima.dao.UserDao.findAll");
//遍历结果集
for (Object o : list) {
System.out.println(o);
}
//关闭资源
sqlSession.close();
}
}
五、mybatis实现CRUD
a、mybatis 的中文文档网址:http://www.mybatis.org/mybatis-3/zh/getting-started.html
b、 selectList 查询多个对象,返回一个list集合(也能查询一个)
selectOne: 查询单个对象,返回一个对象
c、日志记录日常操作
引入依赖:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
引入日志的配置文件:log4j.properties
d、增删改查
<!--UserMapper删除操作-->
<delete id="del" parameterType="java.lang.Integer">
delete from user where id = #{id}
</delete>
<!--测试类-->
@Test
public void testDel(){
//获取输入流对象
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("SqlMapConfig.xml");
//获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
//获取的sqlsession不能自动提交
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql语句
sqlSession.delete("userMapper.del",3);
//提交:只要修改了数据库必须提交
sqlSession.commit();
sqlSession.close();
}
e、模糊查询
参数: %a%
配置文件: username like #{username}
参数: a
配置文件1: username like "%"#{username}"%"
配置文件2: username like "%${value}%"
如果传的是简单类型必须使用value
如果是pojo,属性名引用
d、参数
简单类型: 基本数据类型,String
如果${} 必须用value引用
如果#{} 随便写
pojo类型:属性名引用
e、${} 与 #{}区别
${}:直接拼接,不会转换类型, 不能防注入
#{}:转换类型后拼接, 相当于占位符?,可以防注入
六、核心配置文件详解
1. 配置文件中的标签和顺序
properties?, 配置属性(学习)
settings?, 全局配置:缓存,延迟加载
typeAliases?, 类型别名(学习)
typeHandlers?, 类型转换(操作)(了解)
objectFactory?, objectWrapperFactory?, reflectorFactory?,
plugins?, 插件:分页插件
environments?, 环境配置(数据源)
databaseIdProvider?,
mappers? 引入映射配置文件(学习)
? : 一个或者零个
| : 任选其一
+ : 最少一个
* : 零个或多个
, : 必须按照此顺序编写
七、输入参数类型和输出参数类型
1. 输入参数
简单类型: 基本数据类型+ String类型
#{} :名称随便
${} :${value}
pojo 类型
#{} :${} : 属性名引用
包装对象类型
引用 #{属性.属性名}
Map集合
引用: #{key}
多个参数
引用时:#{param1},#{param2}.....#{paramN}
2. 返回值类型
如果列与属性名不一致,对应的属性为null, 必须写映射配置
八、mybatis自带数据源
<!--数据库的环境:
default; 指定默认的环境
-->
<environments default="development">
<!--id: 环境唯一的标志 -->
<environment id="development">
<!--事务管理: jdbc-->
<transactionManager type="JDBC"/>
<!--
dataSource: 数据源(数据库连接池)配置
type="POOLED" : 数据源的类型配置
POOLED :使用mybatis的自带数据源配置
UNPOOLED: 不使用数据源配置, 使用Connection操作数据库
JNDI:JNDI服务 数据源配置
-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisdb_331"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
九、事务问题
package com.itheima;
import com.itheima.domain.User;
import org.junit.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* 回顾jdbc代码
*/
public class TestJDBC {
@Test
public void test(){
List<User> userList = new ArrayList<>();
//1. 注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/mybatisdb_331";
String username = "root";
String password = "root";
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
//2. 获取连接
conn = DriverManager.getConnection(url, username ,password);
//事务1 :设置事务手动提交(不能自动提交)
conn.setAutoCommit(false);
// 3. SQL语句
String sql1 = "insert into ......";
String sql2 = "insert into ......";
//4. 创建statement对象: Statement , PreparedStatement
pst = conn.prepareStatement(sql1);
//5. 执行SQL语句,返回结果集
pst.executeUpdate();
pst = conn.prepareStatement(sql2);
pst.executeUpdate();
//事务2:提交事务
conn.commit();
} catch (SQLException e) {
//事务3:出现异常,回顾
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
//事务4: 还原状态,设置事务为自动提交
if(conn != null){
try {
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
//7. 释放资源: 先开后关
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst != null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//打印结果
for (User user : userList) {
System.out.println(user);
}
}
}
十、动态sql语句
1、问题
<!--
多条件查询
如果传递参数个数不对,会出现异常,动态sql可以解决
-->
<select id="findByCondition" resultMap="users" parameterType="user">
select * from user where uname like "%"#{username}"%" and sex = #{sex}
</select>
2、if语句
<!--
多条件查询
-->
<select id="findByCondition" resultMap="users" parameterType="user">
select * from user where 1=1
<if test="username != null">
and uname like "%"#{username}"%"
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</select>
3、where语句
<!--
where : 帮助程序员处理第一个and
多条件 都写上 and关键字
-->
<select id="findByCondition" resultMap="users" parameterType="user">
select * from user
<where>
<if test="username != null">
and uname like "%"#{username}"%"
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</where>
</select>
4、SQL片段
<!--SQL片段
把重复的sql语句提取出来,需要使用时引用即可
id="": 唯一标志
文本:sql语句
-->
<sql id="select_user">select * from user</sql>
-- 关联使用sql片段
-- include :包含
-- refid: 关联的sql片段的id
-- ref :references
<include refid="select_user"></include>
5、foreach语句
<delete id="delByArray" parameterType="integer[]">
delete from user where
<!--
foreach循环标签
collection: 参数的类型:如果是集合:list,如果是数组: array
open :前缀
close:后缀
separator: 分隔符
item: 循环中的每一个对象
index:循环中的索引( 一般不用)
-->
<foreach collection="array" open="uid in (" close=")" separator="," item="id">
#{id}
</foreach>
</delete>
<delete id="delByList" parameterType="list">
delete from user where
<!--
foreach循环标签
collection: 参数的类型:如果是集合:list,如果是数组: array
open :前缀
close:后缀
separator: 分隔符
item: 循环中的每一个对象
index:循环中的索引( 一般不用)
-->
<foreach collection="list" open="uid in (" close=")" separator="," item="id">
#{id}
</foreach>
</delete>
十一、多表关联
1、一对一
a、第一种方法:accountUser extends Account
1)配置文件配置
<resultMap id="accountUsers" type="accountUser">
<result column="uname" property="username"></result>
</resultMap>
<select id="findAllAccountUser" resultMap="accountUsers">
select * from account a, user u where a.u_id = u.uid
</select>
2) pojo配置
/**
* 继承了Account,就拥有Account中所有的属性
* 单独添加User的属性
*/
public class AccountUser extends Account {
private Integer uid;
private String username;
private String password;
private String address;
private Date birthday;
private String sex;
}
3) Dao接口
/**
* 查询所有的账户:包含对应的用户信息
* @return
*/
public List<AccountUser> findAllAccountUser();
b、第二种方法
1)配置文件
<resultMap id="accounts" type="Account">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<result column="money" property="money"></result>
<result column="u_id" property="u_id"></result>
<!--映射user中的属性-->
<result column="uid" property="user.id"></result>
<result column="uname" property="user.username"></result>
<result column="address" property="user.address"></result>
<result column="birthday" property="user.birthday"></result>
<result column="sex" property="user.sex"></result>
<result column="password" property="user.password"></result>
</resultMap>
2)pojo
public class Account {
private Integer id;
private String name;
private Float money;
private Integer u_id;
// 一个账户对应一个用户
private User user;
}
3) Dao接口
/**
* 查询所有的账户:包含对应的用户信息
* @return
*/
public List<Account> findAllAccount();
c、第三种方法
1)配置文件
<resultMap id="accounts" type="Account">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<result column="money" property="money"></result>
<result column="u_id" property="u_id"></result>
<!--映射user中的属性-->
<!--association 映射单个对象
property:属性名
javaType:属性对应的类型
-->
<association property="user" javaType="user">
<id column="uid" property="id"></id>
<result column="uname" property="username"></result>
<result column="address" property="address"></result>
<result column="birthday" property="birthday"></result>
<result column="password" property="password"></result>
<result column="sex" property="sex"></result>
</association>
</resultMap>
2)pojo
public class Account {
private Integer id;
private String name;
private Float money;
private Integer u_id;
// 一个账户对应一个用户
private User user;
}
3) Dao接口
/**
* 查询所有的账户:包含对应的用户信息
* @return
*/
public List<Account> findAllAccount();
2、一对多
a. pojo
public class User {
private Integer id;
private String username;
private String password;
private String address;
private Date birthday;
private String sex;
//一个用户对应多个账户
private List<Account> accountList;
}
b. 配置文件
<resultMap id="users" type="User">
<id column="uid" property="id"></id>
<result column="uname" property="username"></result>
<result column="password" property="password"></result>
<result column="address" property="address"></result>
<result column="birthday" property="birthday"></result>
<result column="sex" property="sex"></result>
<!--Collection : 映射accountList 属性
property: 对应的属性名
ofType: 集合中的元素类型: association 中javaType效果一致
-->
<collection property="accountList" ofType="account">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<result column="money" property="money"></result>
<result column="u_id" property="u_id"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="users">
select * from user u left join account a on u.uid = a.u_id
</select>
c、Dao接口
/**
* 返回所有的user对象,包含用户对应账户信息
* @return
*/
public List<User> findAll();
3、多对多
a. sql语句
create table role(
id int primary key auto_increment,
roleName varchar(20),
roleDesc varchar(20)
)
create table user_role(
uid int ,
rid int ,
-- 联合主键: 两列以上为主键列, 两列不能同时相同
primary key(uid,rid),
foreign key(uid) references user(uid),
foreign key(rid) references role(id)
)
b. pojo
public class User {
private Integer id;
private String username;
private String password;
private String address;
private Date birthday;
private String sex;
// 一个用户有多个角色
private List<Role> roleList;
}
c、配置文件
<mapper namespace="com.itheima.dao.UserDao">
<resultMap id="users" type="user">
<id column="uid" property="id"></id>
<result column="uname" property="username"></result>
<result column="address" property="address"></result>
<result column="birthday" property="birthday"></result>
<result column="sex" property="sex"></result>
<result column="password" property="password"></result>
<!--一个用户对应多个角色: roleList-->
<collection property="roleList" ofType="role">
<id column="id" property="id"></id>
<result column="roleName" property="roleName"></result>
<result column="roleDesc" property="roleDesc"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="users">
select u.* ,r.* from user u left join user_role ur on u.uid = ur.uid left join role r on r.id = ur.rid
</select>
</mapper>
d、dao接口
/**
* 返回所有的user对象,包含用户对应的角色对象
* @return
*/
public List<User> findAll();
角色到用户的关系
a、pojo
public class Role {
private Integer id;
private String roleName;
private String roleDesc;
// 一个角色对应多个用户'
private List<User> userList;
}
b、配置文件
<mapper namespace="com.itheima.dao.RoleDao">
<resultMap id="roles" type="role">
<id column="id" property="id"></id>
<result column="roleName" property="roleName"></result>
<result column="roleDesc" property="roleDesc"></result>
<collection property="userList" ofType="User">
<id column="uid" property="id"></id>
<result column="uname" property="username"></result>
<result column="address" property="address"></result>
<result column="birthday" property="birthday"></result>
<result column="sex" property="sex"></result>
<result column="password" property="password"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="roles">
select r.*,u.* from role r left join user_role ur on r.id = ur.rid left join user u on u.uid = ur.uid
</select>
</mapper>
c、dao接口
/**
* 查询所有的角色,包含用户对象
* @return
*/
public List<Role> findAll();
Mybatis推荐书籍
以下是一些关于 MyBatis 的书籍推荐及其推荐理由:
1.《MyBatis技术内幕》:这本书讲解了 MyBatis 的核心原理和实现细节,适合想要深入了解 MyBatis 的同学。
2.《MyBatis实战》:这本书通过实例演示了如何使用 MyBatis 进行数据库操作,适合初学者入门。
3.《MyBatis从入门到精通》:这本书从基础到高级全面介绍了 MyBatis 的使用,适合想要系统学习 MyBatis 的同学。
4.《MyBatis源码解析》:这本书详细分析了 MyBatis 的源代码,并讲解了其实现原理,适合想要深入研究 MyBatis 的同学。
5.《MyBatis开发经验谈》:这本书分享了一些作者在实际项目中使用 MyBatis 的经验和技巧,适合有一定经验的开发人员参考。
希望对你有所帮助~

1018

被折叠的 条评论
为什么被折叠?



