banner
NEWS LETTER

Mybatis持久层框架

Scroll down

MyBatis

什么是MyBatis

  • MyBatis是一款优秀的持久层框架,用于简化JDBC开发
    • 持久层

​ 负责将数据到保存到数据库的那一层代码

​ JavaEE三层架构:表现层、业务层、持久层

MyBatis快速入门/Mapper代理开发

使用MyBatis查询表中的所有信息

(1)安装MyBatis

1
2
3
4
5
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>

(2)创建mybatis核心配置文件mybatis-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="510609"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载SQL映射-->
<mapper resource="com/UserMapper.xml"/>
</mappers>
</configuration>

(3)定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下

UserMapper.java****:

1
2
3
4
5
6
7
8
package com.dome;
import pojo.User;

import java.util.List;

public interface UserMapper {
List<User> selectAll();
}

resultType:可选pojo,预计返回值类型

id是接口中的方法名

设置SQL映射的namespace属性为Mapper接口全限定名

1
2
3
4
5
6
7
8
9
10
11
12
<?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.dome.UserMapper">
<select id="selectAll" resultType="pojo.User">
select * from tb_user;
</select>
</mapper>

(4) 在实体类中调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
/*1.加载mybatis的核心配置文件,获取SqlSessionFactory*/
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);


/*2.获取SqlSessionFactory对象,用它来执行sql*/
SqlSession sqlSession=sqlSessionFactory.openSession();

/*3.执行sql*/
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
List<User> users=userMapper.selectAll();

System.out.println(users);

/*4.释放资源*/
sqlSession.close();
}
}

MyBatis核心配置文件设置

:配置数据库连接环境信息,可以配置多个environment,通过default属性切换不同的environment

:指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

1
2
3
<typeAliases>
<package name="com.demo.pojo"/>
</typeAliases>

MyBatis之查询

接口:

1
2
3
4
public interface BrandMapper {
/*查询所有*/
String selectById();
}

sql语句设置:

1
2
3
4
5
<mapper namespace="com.demo.mapper.BrandMapper">
<select id="selectById" resultType="String">
select brandName from tb_brand where id=#{id}
</select>
</mapper>

获取返回值

1
2
3
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);

String brand= brandMapper.selectById(id);

多条件查询

接口这样写:

1
List<Brand> selectByCondition(@Param("status") int status,@Param("companyName") String companyName,@Param("brandName") String brandName);

SQL语句设置:

1
2
3
4
5
6
7
8
9
<mapper namespace="com.demo.mapper.BrandMapper">   
<!--多条件/模糊查询-->
<select id="selectByCondition" resultType="Brand">
select * from tb_brand
where status = #{status}
and companyName like #{companyName}
and brandName like #{brandName}
</select>
</mapper>

获取查询到的数据:

1
2
3
4
5
6
7
8
9
10
11
12
int status=1;
String companyName="华为";
String brandName="华为";
/*处理参数*/
companyName="%"+companyName+"%";
brandName="%"+brandName+"%";



List<Brand> list=brandMapper.selectByCondition(status,companyName,brandName);
System.out.println(list);

选择性多条件查询

在日常使用中,有时候可能用户不会填写所有的条件,而是选填一部分对此可以:

sql语句:

if标签判断是否为空

where用来解决and造成的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<select id="selectByCondition" resultType="Brand">
select * from tb_brand
<where>
<if test="status!=null">
status = #{status}
</if>
<if test="companyName!=null and companyName!='' ">
and companyName like #{companyName}
</if>
<if test="brandName!=null and brandName!='' ">
and brandName like #{brandName}
</if>
</where>
</select>

单条件查询

在使用时经常使用下拉列表进行单项查询,所以使用类似于switch进行选择判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<select id="selectByCondition" resultType="Brand">
select * from tb_brand
<where>
<choose> /*类似于switch*/
<when test="status!=null"> /*类似于case选项*/
status = #{status}
</when>
<when test="companyName!=null and companyName!='' ">
and companyName like #{companyName}
</when>
<when test="brandName!=null and brandName!='' ">
and brandName like #{brandName}
</when>
<otherwise> /*类似于default*/
1=1
</otherwise>
</choose>
</where>
</select>

添加元素

接口添加:

1
void add(Brand brand);

sql语句:

1
2
3
4
5
6
7
8
9
10
<insert id="add">
insert into tb_brand(brandName,companyName,ordered,description,status)
values (
#{brandName},
#{companyName},
#{ordered},
#{description},
#{status}
)
</insert>

添加数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
      int status=1;
String companyName="Samsung";
String brandName="三星";
String description="手机中的战斗机";
int ordered=100;

/*封装对象*/
Brand brand=new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

SqlSession sqlSession=sqlSessionFactory.openSession();

/*获取UserMapper的接口的代理对象*/
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
brandMapper.add(brand);

/*提交事务*/
sqlSession.commit();

如果不想提交事务,可以在

SqlSession sqlSession=sqlSessionFactory.openSession();

openSession中填true即可自动添加

返回主键操作:

1
<insert id="add" useGeneratedKeys="true" keyProperty="id">

修改全部字段

接口修改:

1
int update(Brand brand);

sql语句:

1
2
3
4
5
6
7
8
9
<update id="update">
update tb_brand
set brandName=#{brandName},
companyName=#{companyName},
ordered=#{ordered},
description=#{description},
status=#{status}
where id=#{id};
</update>

修改数据操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
int status=1;
String companyName="博导";
String brandName="博导手机";
String description="手机中的战斗机";
int ordered=200;
int id =3;

/*封装对象*/
Brand brand=new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
brand.setId(id);

/*处理参数*/
companyName="%"+companyName+"%";
brandName="%"+brandName+"%";

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

SqlSession sqlSession=sqlSessionFactory.openSession();

/*获取UserMapper的接口的代理对象*/
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);

int count=brandMapper.update(brand);
System.out.println(count);

sqlSession.commit();

/*4.释放资源*/
sqlSession.close();

删除

接口文件:

1
void deleteById(int id);

sql映射:

1
2
3
<delete id="deleteById">
delete from tb_brand where id=#{id}
</delete>

删除操作:

1
2
3
4
5
int id =3;

brandMapper.deleteById(id);

sqlSession.commit();

批量删除

接口文件

1
void deleteByIds(@Param("ids")int[] ids);

sql映射

1
2
3
4
5
6
7
8
<delete id="deleteByIds">
delete from tb_brand where id
in(
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
)
</delete>

批量删除操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int[] ids={2,3,53};
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

SqlSession sqlSession=sqlSessionFactory.openSession();

/*获取UserMapper的接口的代理对象*/
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);

brandMapper.deleteByIds(ids);

sqlSession.commit();
/*4.释放资源*/
sqlSession.close();

注解开发

使用注解开发会比配置文件开发更加方便

在接口中写:

1
2
@Select("select * from tb_user where id=#{id}")
public User selectById(int id);

查询:@Select

添加:@Insert

修改:@Update

删除:@Delete

Other Articles
cover
SSM整合
  • 23/03/15
  • 16:35
  • 2.2k
  • 12
cover
Spring笔记
  • 23/03/07
  • 09:40
  • 4.8k
  • 22