1.概念
持久层框架,用于简化JDBC
2.Mybatis入门案例
1.新建user数据库表
2.idea中新建Maven项目,导入相关依赖
<dependencies>
<!--mybatis 依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!--junit 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- 添加slf4j日志api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<!-- 添加logback-classic依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- 添加logback-core依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
3.新建logback.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--
CONSOLE :表示当前的日志信息是可以输出到控制台的。
-->
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
</encoder>
</appender>
<logger name="com.itheima" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
<!--
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
, 默认debug
<root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
-->
<root level="DEBUG">
<appender-ref ref="Console"/>
</root>
</configuration>
4.新建mybatis-config.xml文件,加载数据库连接信息和加载sql映射文件
<?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>
<!--<typeAliases>
<package name="com.itheima.pojo"/>
</typeAliases>
-->
<!--
environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
-->
<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?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/Mybatis?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="UserMapper.xml"/>
<!--Mapper代理方式-->
<!-- <package name="com.itheima.mapper"/>-->
</mappers>
</configuration>
5.创建sql映射文件
<?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="test"> <!--命名空间-->
<select id="findAll" resultType="Pojo.User"> <!--唯一标识,返回值类型-->
select * from user;
</select>
</mapper>
6.编写实体类
public class User {
private Integer id ;
private String username;
private String password;
private String email ;
private String addr ;
public User() {
}
public User(Integer id, String username, String password, String email, String addr) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.addr = addr;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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 + '\'' +
", email='" + email + '\'' +
", addr='" + addr + '\'' +
'}';
}
}
7.编写测试类
public class Main {
public static void main(String[] args) {
String resource="mybatis-config.xml";
SqlSession sqlSession=null;
try {
//加载Mybatis的核心配置文件,获取SqlSessionFactory
InputStream resourceAsStream = Resources.getResourceAsStream(resource);
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获取sqlSession对象用于执行sql
sqlSession = build.openSession();
//执行sql
List<Object> objects = sqlSession.selectList("test.findAll");//命名空间
System.out.println(objects.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (sqlSession!=null) {
sqlSession.close();
}
}
}
}
3.Mapper代理
1.定义sql映射文件同名同路径的mapper接口,并且将mapper接口和sql映射文件放在同一个目录下(创建文件的方式用/分割方式)
2.设置sql映射文件namespace属性为mapper接口的全类名
<mapper namespace="Dao.UserMapper">
<select id="findAll" resultType="Pojo.User">
select * from user;
</select>
</mapper>
3.在mapper中定义方法,方法名为sql映射文件中sql语句上的id值,并保证参数和返回值类型一致。
public interface UserMapper {
List<User> findAll();
}
4.开启mapper代理
<mappers>
<!--加载sql映射文件-->
<!-- <mapper resource="Dao.UserMapper.xml"/>-->
<!--Mapper代理方式-->
<package name="Dao"/>
</mappers>
5.执行
package Main;
import Dao.UserMapper;
import 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 Main {
public static void main(String[] args) {
String resource="mybatis-config.xml";
SqlSession sqlSession=null;
try {
//加载Mybatis的核心配置文件,获取SqlSessionFactory
InputStream resourceAsStream = Resources.getResourceAsStream(resource);
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获取sqlSession对象用于执行sql
sqlSession = build.openSession();
//执行sql
/* List<Object> objects = sqlSession.selectList("test.findAll");//命名空间*/
UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
List<User> all = usermapper.findAll();
System.out.println(all.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (sqlSession!=null) {
sqlSession.close();
}
}
}
}
5.Mybatis核心配置
1.<environments></environments>标签
配置数据库连接环境信息,里面可以配置多个<environment><environment>标签,environments通过default属性切换不同的environment,连接数据库
2.<mappers></mappers>标签
用于加载sql映射文件
3.<typeAliases></typeAliases>标签
用于设置别名实体类的别名,在mapper.xml中返回值类型可以直接写实体类名字
<typeAliases>
<package name="Pojo"/>
</typeAliases>
<select id="findAll" resultType="User">
select * from user;
</select>
4.核心配置文件的标签配置时需要注意先后顺序,不然报错
6.配置文件完成增、删、改、查操作
环境准备
新建库建表、新建实体类,测试类、插入MybatisX插件
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
private Integer status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
public class Utils {
public static String resource="mybatis-config.xml";
public static SqlSession sqlSessionCon(){
//加载Mybatis的核心配置文件,获取SqlSessionFactory
InputStream resourceAsStream = null;
try {
resourceAsStream = Resources.getResourceAsStream(resource);
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获取sqlSession对象用于执行sql
SqlSession sqlSession = build.openSession();
return sqlSession;
} catch (IOException e) {
e.printStackTrace();
}
throw new RuntimeException();
}
public static void sqlSessionClose(SqlSession sqlSession){
sqlSession.close();
}
}
1.查询所有记录
a.遇到数据库字段名和数据库对应实体类姓名不一致问题可以采用如下三种解决方案:
1)通过建立别名的方式
<select id="selectfindAll" resultType="Brand">
select id,brand_name as brandName,company_name as companyName,ordered,description,status from tb_brand;
</select>
2)通过sql片段的方式
<sql id="brand_name">
id,brand_name as brandName,company_name as companyName,ordered,description,status
</sql>
<select id="selectfindAll" resultType="Brand">
select <include refid="brand_name"></include> from tb_brand;
</select>
3)通过Mybatis提供的resultMap
<resultMap id="brandResultMap" type="Brand">
<id column="id" property="id"></id>
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<select id="selectfindAll" resultMap="brandResultMap">
select * from tb_brand;
</select>
b.测试
List<Brand> selectfindAll();
@Test
public void test01(){
SqlSession sqlSession = Utils.sqlSessionCon();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
List<Brand> brands = mapper.selectfindAll();
System.out.println(brands.toString());
Utils.sqlSessionClose(sqlSession);
}
<resultMap id="brandResultMap" type="Brand">
<id column="id" property="id"></id>
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<select id="selectfindAll" resultMap="brandResultMap">
select * from tb_brand;
</select>
2.单条查询-静态查询
a.查询指定信息时参数占位符#{}、${}
b.处理特殊符号
1)转义特殊字符 id < #{id};
2)CDATA格式 <![CDATA[<]]>
Brand selectfindId(Integer id);
<resultMap id="brandResultMap" type="Brand">
<id column="id" property="id"></id>
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<select id="selectfindId" resultMap="brandResultMap">
select * from tb_brand where id=#{id};
</select>
@Test
public void test02(){
SqlSession sqlSession = Utils.sqlSessionCon();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand brands = mapper.selectfindId(1);
System.out.println(brands.toString());
Utils.sqlSessionClose(sqlSession);
}
3.单条查询-动态sql查询(两个框框的联动查询)
动态查询时如条件都不会符合可以用 <otherwise>1=1</otherwise>恒等式标签,也可以将where换成<where></where>标签包裹
Brand selectfindIdy(Brand brand);
<select id="selectfindIdy" resultMap="brandResultMap">
select *
from tb_brand
where
<choose>
<when test="id!=null">
id=#{id}
</when>
<when test="brandName!=null and brandName!=''">
brand_name like #{BrandName}
</when>
<when test="companyName!=null and companyName!=''">
company_name like #{companyName}
</when>
<when test="ordered!=null">
ordered=#{ordered}
</when>
<when test="description!=null and description!=''">
description like #{description}
</when>
<when test="status!=null">
status=#{status}
</when>
<otherwise>
1=1
</otherwise>
</choose>
;
</select>
<select id="selectfindIdy" resultMap="brandResultMap">
select *
from tb_brand
<where>
<choose>
<when test="id!=null">
id=#{id}
</when>
<when test="brandName!=null and brandName!=''">
brand_name like #{BrandName}
</when>
<when test="companyName!=null and companyName!=''">
company_name like #{companyName}
</when>
<when test="ordered!=null">
ordered=#{ordered}
</when>
<when test="description!=null and description!=''">
description like #{description}
</when>
<when test="status!=null">
status=#{status}
</when>
</choose>
</where>
;
</select>
@Test
public void test03(){
SqlSession sqlSession = Utils.sqlSessionCon();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand brand=new Brand();
String desc="好吃";
desc="%" + desc + "%";
List<Brand> brands = mapper.selectfindIdy(brand);
System.out.println(brands.toString());
Utils.sqlSessionClose(sqlSession);
}
4.多条查询-静态查询
a.条件查询时,参数传递问题:
1)散装参数传递 用@Param注解
List<Brand> selectLinkagefind(@Param("status")Integer status,@Param("brandName")String brandName,@Param("companyName")String companyName);
2)对象参数传递
List<Brand> selectLinkagefind(Brand brand);
3)map集合参数
/*List<Brand> selectLinkagefind(@Param("status")Integer status,@Param("brandName")String brandName,@Param("companyName")String companyName);*/
/*List<Brand> selectLinkagefind(Brand brand);*/
List<Brand> selectLinkagefind(Map map);
<select id="selectLinkagefind" resultMap="brandResultMap">
select * from tb_brand
where status=#{status}
and brand_name like #{brandName}
and company_name like #{companyName}
</select>
@Test
public void test04(){
SqlSession sqlSession = Utils.sqlSessionCon();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand brand=new Brand();
Integer status=1;
String brandName="华为";
String companyName="华为";
brandName="%" + brandName + "%";
companyName="%" + companyName + "%";
/* brand.setStatus(1);
brand.setBrandName(brandName);
brand.setCompanyName(companyName);*/
Map map=new HashMap();
map.put("status",status);
map.put("brandName",brandName);
map.put("companyName",companyName);
List<Brand> brands = mapper.selectLinkagefind(map);
System.out.println(brands.toString());
Utils.sqlSessionClose(sqlSession);
}
5.多条查询-动态sql查询(多框框联动操作)
List<Brand> selectLinkagefinddy(Map map);
<select id="selectLinkagefinddy" resultMap="brandResultMap">
select * from tb_brand
where 1=1
<if test="status!=null">
and status=#{status}
</if>
<if test="brandName!=null and brandName!=''">
and brand_name like #{brandName}
</if>
<if test="companyName!=null and companyName!=''">
and company_name like #{companyName};
</if>
</select>
<select id="selectLinkagefinddy" resultMap="brandResultMap">
select * from tb_brand
<where>
<if test="status!=null">
and status=#{status}
</if>
<if test="brandName!=null and brandName!=''">
and brand_name like #{brandName}
</if>
<if test="companyName!=null and companyName!=''">
and company_name like #{companyName};
</if>
</where>
</select>
@Test
public void test05(){
SqlSession sqlSession = Utils.sqlSessionCon();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand brand=new Brand();
Integer status=1;
String brandName="华为";
String companyName="华为";
brandName="%" + brandName + "%";
companyName="%" + companyName + "%";
Map map=new HashMap();
map.put("status",status);
map.put("brandName",brandName);
map.put("companyName",companyName);
List<Brand> brands = mapper.selectLinkagefinddy(map);
System.out.println(brands.toString());
Utils.sqlSessionClose(sqlSession);
}
6.添加记录
在添加记录的时候需要手动开启事务提交,mybatis中自动将自动提交设置为false,添加数据后进行主键返回需要在<insert></insert>中设置 useGeneratedKeys="true" keyProperty="id"属性
Integer insertAll(Map map);
<insert id="insertAll" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand values (#{id},#{brandName},#{companyName},#{ordered},#{description},#{status});
</insert>
@Test
public void test06(){
SqlSession sqlSession = Utils.sqlSessionCon();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand brand=new Brand();
String brandName="小米out";
Integer id=6;
String companyName="小米快淘汰了";
Integer ordered=20;
String description="哈哈哈哈哈";
Integer status=1;
Map map=new HashMap();
map.put("brandName",brandName);
map.put("id",id);
map.put("companyName",companyName);
map.put("ordered",ordered);
map.put("description",description);
map.put("status",status);
Integer integer = mapper.insertAll(map);
sqlSession.commit();
System.out.println(integer);
Utils.sqlSessionClose(sqlSession);
}
7.修改全部字段
在修改记录的时候需要手动开启事务提交,mybatis中自动将自动提交设置为false
Integer updateAll(Map map);
<update id="updateAll">
update tb_brand
set brand_name=#{brandName},
company_name=#{companyName},
ordered=#{ordered},
description=#{description}
where id=#{id}
</update>
@Test
public void test07(){
SqlSession sqlSession = Utils.sqlSessionCon();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand brand=new Brand();
String brandName="小米out111";
Integer id=6;
String companyName="小米没淘汰111";
Integer ordered=25;
String description="哈哈哈111";
Map map=new HashMap();
map.put("brandName",brandName);
map.put("id",id);
map.put("companyName",companyName);
map.put("ordered",ordered);
map.put("description",description);
Integer integer = mapper.updateAll(map);
System.out.println(integer);
sqlSession.commit();
Utils.sqlSessionClose(sqlSession);
}
8.修改动态字段
在修改记录的时候需要手动开启事务提交,mybatis中自动将自动提交设置为false
Integer updateAlldy(Map map);
<update id="updateAlldy">
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 and ordered!=''">
ordered=#{ordered},
</if>
<if test="description!=null and description!=''">
description=#{description},
</if>
<if test="status!=null">
status=#{status}
</if>
</set>
where id=#{id};
</update>
@Test
public void test08(){
SqlSession sqlSession = Utils.sqlSessionCon();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
String brandName="小米555";
Integer id=5;
String companyName="小米555";
Integer ordered=32;
String description="小米哈哈哈555";
Integer status=0;
Map map=new HashMap();
map.put("brandName",brandName);
map.put("id",id);
map.put("companyName",companyName);
map.put("ordered",ordered);
map.put("description",description);
map.put("status",status);
Integer integer = mapper.updateAlldy(map);
sqlSession.commit();
System.out.println(integer);
Utils.sqlSessionClose(sqlSession);
}
9.单条删除
在删除记录的时候需要手动开启事务提交,mybatis中自动将自动提交设置为false
Integer deleteCount(Map map);
<delete id="deleteCount">
delete from tb_brand
where id=#{id};
</delete>
@Test
public void test09(){
SqlSession sqlSession = Utils.sqlSessionCon();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
String brandName="小米555";
Integer id=5;
String companyName="小米555";
Integer ordered=32;
String description="小米哈哈哈555";
Integer status=0;
Map map=new HashMap();
map.put("brandName",brandName);
map.put("id",id);
map.put("companyName",companyName);
map.put("ordered",ordered);
map.put("description",description);
map.put("status",status);
Integer integer = mapper.deleteCount(map);
sqlSession.commit();
System.out.println(integer);
Utils.sqlSessionClose(sqlSession);
}
10.动态批量删除(静态批量删除时where id in (?,?))
在删除记录的时候需要手动开启事务提交,mybatis中自动将自动提交设置为false
a.传递的参数为Map类型时,collection属性值为"array"
delete id="deleteAll">
delete from tb_brand
where id in (
<foreach collection="array" item="id" separator="," open="(" close=")">
#{id}
</foreach>
);
</delete>
b.传递参数时是数组则运用@Param传递参数
Integer deleteAll(@Param("ids")Integer[] ids);
<delete id="deleteAll">
delete from tb_brand
where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
;
</delete>
@Test
public void test10(){
SqlSession sqlSession = Utils.sqlSessionCon();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Integer[] ids={3,4};
Integer integer = mapper.deleteAll(ids);
sqlSession.commit();
System.out.println(integer);
Utils.sqlSessionClose(sqlSession);
}
7.参数传递机制
多个参数传递时必须引用@Param注解或Map传递xml中用array,单个参数时可以直接传递前后名字对应,可以用类传递,map接口传递
8.注解开发完成增、删、改、查
@Select("select * from tb_brand where id =#{id}")
Brand selectAllFindID(Integer id);