持久层框架
,用于简化JDBC开发。持久层
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作
CREATE DATABASE mybatis; -- 创建一个数据库,名为mybatis
USE mybatis; -- 使用 mybaits
DROP TABLE if EXISTS tb_user; -- 若 tb_user 表存在,删除该表
-- 创建 tb_user 表
CREATE TABLE tb_user {
id int PRIMARY KEY auto_increment,
username VARCHAR(20),
password VARCHAR(20),
gender CHAR(1),
addr VARCHAR(30)
);
-- 添加数据
INSERT INTO tb_user VALUES(1, '张三', '123', '男', '北京');
INSERT INTO tb_user VALUES(2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES(3, '王五', '11', '男', '西安');
在 pom.xml 配置文件中添加依赖
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.30version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>jcl-over-slf4jartifactId>
<version>1.5.6version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-coreartifactId>
<version>1.2.3version>
dependency>
dependencies>
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="UserMapper.xml"/>
mappers>
configuration>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<select id="selectAll" resultType="com.itheima.pojo.User">
select * from tb_user;
select>
mapper>
映射文件取名讲究
表名Mapper.xml
定义user类
package com.itheima.pojo;
// alt + 鼠标左键 整列编辑
public class User {
private int id;
private String username;
private String password;
private String gender;
private String addr;
public int getId() {
return id;
}
public void setId(int 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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", addr='" + addr + '\'' +
'}';
}
}
编写核心测试类 MyBatisDemo.java
package com.itheima;
import com.itheima.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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
// 1. 加载mybatis 的核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml"; // MyBatis核心配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2. 获取SqlSession 对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3. 执行sql
List<User> users = sqlSession.selectList("test.selectAll"); // 用空间名称和sql 语句的 id ,对sql语句进行辨别
System.out.println(users);
/*
[User{id=1, username='张三', password='123', gender='男', addr='北京'},
User{id=2, username='李四', password='234', gender='女', addr='天津'},
User{id=3, username='王五', password='11', gender='男', addr='西安'}]
*/
// 4. 释放资源
sqlSession.close();
}
}
目的:
细节:
如果 Mapper 接口名称和 SQL 映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化 SQL 映射文件的加载
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.itheima.pojo"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.itheima.mapper"/>
mappers>
configuration>
自定义别名
1)myBatis 核心配置文件中设置别名
2)***Mapper.xml 文件中使用别名
MyBatisX
是一款基于IDEA的快速开发插件,为效率而生。
主要功能:
实体类属性和数据库表列名不一致,不能自动封装数据
1)起别名
:在sql语句中,对不一样的列名起别名,别名和实体类属性名一样
2)resultMap
:定义完成不一致的属性名和列名的映射
参数占位符
:
- 参数传递的时候:
#{}
- 表名或列名不固定的情况下:
${}
,会存在SQL注入问题
特殊字符处理
:
SQL语句设置多个参数的三种方式:
<select id="selectByCondition0" resultMap="brandResultMap">
select *
from tb_brand
where status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName};
select>
<select id="selectByCondition1" resultMap="brandResultMap">
select *
from tb_brand
<where>
<if test="status != null">
and status = #{status}
if>
<if test="companyName != null and companyName != ''">
and company_name like #{companyName}
if>
<if test="brandName != null and brandName != ''">
and brand_name like #{brandName}
if>
where>
select>
<select id="selectByCondition2" resultMap="brandResultMap">
select *
from tb_brand
<where>
<choose>
<when test="status != null">
status = #{status}
when>
<when test="companyName != null and companyName != ''">
company_name like #{companyName}
when>
<when test="brandName != null and brandName != ''">
brand_name like #{brandName}
when>
choose>
where>
select>
<insert id="add">
insert into tb_brand (brand_name, company_name, ordered, description, status)
values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
insert>
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand (brand_name, company_name, ordered, description, status)
values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
insert>
<update id="update">
update tb_brand
set brand_name = #{brandName},
company_name = #{companyName},
ordered = #{ordered},
description = #{description},
status = #{status}
where id = #{id};
update>
<update id="update">
update tb_brand
<set>
<if test="brandName != null and brandName != ''">
brand_name = #{brandName},
if>
<if test="companyName != null and companyName != ''">
company_name = #{companyName},
if>
<if test="ordered != null">
ordered = #{ordered},
if>
<if test="description != null and description != ''">
description = #{description},
if>
<if test="status != null">
status = #{status}
if>
set>
where id = #{id};
update>
使用注解来映射简单语句会使代码显得更加简洁
,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的SQL语句更加混乱不堪。因此,如果你需要做一些很复杂的操作,最好
用XML来映射语句。
选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和XML的语句映射方式间自
由移植和切换。