MyBatis基础操作

 1. 什么是MyBatis?

MyBatis是⼀款优秀的 持久层 框架,⽤于简化JDBC的开发

总结:简单来说 MyBatis 是更简单完成程序和数据库交互的框架,也就是更简单的操作和读取数据库⼯具

2.MyBatis⼊⻔

1. 准备⼯作(创建springboot⼯程、数据库表准备、实体类)

2. 引⼊Mybatis的相关依赖,配置Mybatis(数据库连接信息)

3. 编写SQL语句(注解/XML)

4. 测试

2.1 准备⼯作

2.1.1 创建⼯程

创建springboot⼯程,并导⼊ mybatis的起步依赖、mysql的驱动包

useGeneratedKeys:这会令 MyBatis 使⽤ JDBC 的 getGeneratedKeys ⽅法来取出由数据库内
部⽣成的主键(⽐如:像 MySQL 和 SQL Server 这样的关系型数据库管理系统的⾃动递增字
段),默认值:false.
keyProperty:指定能够唯⼀识别对象的属性,MyBatis 会使⽤ getGeneratedKeys 的返回值或
insert 语句的 selectKey ⼦元素设置它的值,默认值:未设置(unset)

PS:Mybatis 是⼀个持久层框架, 具体的数据存储和数据操作还是在MySQL中操作的, 所以需要添加 MySQL驱动

项⽬⼯程创建完成后,⾃动在pom.xml⽂件中,导⼊Mybatis依赖和MySQL驱动依赖

1 <!--Mybatis 依赖包-->
2 <dependency>
3 <groupId>org.mybatis.spring.boot</groupId>
4 <artifactId>mybatis-spring-boot-starter</artifactId>
5 <version>2.3.1</version>
6 </dependency>
7 <!--mysql驱动包-->
8 <dependency>
9 <groupId>com.mysql</groupId>
10 <artifactId>mysql-connector-j</artifactId>
11 <scope>runtime</scope>
12 </dependency>

2.2 配置数据库连接字符串

Mybatis中要连接数据库,需要数据库相关参数配置

• MySQL驱动类

• 登录名

• 密码

• 数据库连接字符串

如果是application.yml⽂件, 配置内容如下:

1 # 数据库连接配置

2 spring:

3 datasource:

4 url: jdbc:mysql://127.0.0.1:3306/mybatis_test?

characterEncoding=utf8&useSSL=false

5 username: root

6 password: root

7 driver-class-name: com.mysql.cj.jdbc.Driver

 如果是application.properties⽂件, 配置内容如下:

1 #驱动类名称

2 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3 #数据库连接的url

4 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_test?

characterEncoding=utf8&useSSL=false

5 #连接数据库的⽤⼾名

6 spring.datasource.username=root

7 #连接数据库的密码

8 spring.datasource.password=root

2.3 写持久层代码

//示例
 @Mapper
 public interface UserInfoMapper {
 //查询所有⽤⼾
 @Select("select username, `password`, age, gender, phone from userinfo")
 public List<UserInfo> queryAllUser();
 }
  1. Mybatis的持久层接⼝规范⼀般都叫 XxxMapper
  2. @Mapper注解:表⽰是MyBatis中的Mapper接⼝
程序运⾏时, 框架会⾃动⽣成接⼝的实现类对象(代理对象),并给交Spring的IOC容器管理
@Select注解:代表的就是select查询,也就是注解对应⽅法的具体实现内容.

2.4 单元测试

9 @SpringBootTest
10 class DemoApplicationTests {
11
12 @Autowired
13 private UserInfoMapper userInfoMapper;
14
15 @Test
16 void contextLoads() {
17 List<UserInfo> userInfoList = userInfoMapper.queryAllUser();
18 System.out.println(userInfoList);
19 }
20 }
  • 测试类上添加了注解 @SpringBootTest,该测试类在运⾏时,就会⾃动加载Spring的运⾏环境.
  • @Autowired这个注解, 注⼊我们要测试的类, 就可以开始进⾏测试了

3. MyBatis的基础操作

3.1 打印⽇志

  • 在Mybatis当中我们可以借助⽇志, 查看到sql语句的执⾏、执⾏传递的参数以及执⾏结果
配置⽂件中进⾏配置
1 mybatis:
2 configuration: # 配置打印 MyBatis ⽇志
3 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
如果是application.properties, 配置内容如下
1 # 指定 mybatis 输出⽇志的位置 , 输出控制台
2 mybatis.configuration.log-impl = org.apache.ibatis.logging.stdout.StdOutImpl

3.2 参数传递 

需求: 查找id=4的⽤⼾,对应的SQL就是: select * from userinfo where id=4
1 @Select("select username, `password`, age, gender, phone from userinfo where
id= 4 ")
2 UserInfo queryById ();
  • 但是这样的话, 只能查找id=4 的数据, 所以SQL语句中的id值不能写成固定数值,需要变为动态的数值
  • 解决⽅案:在queryById⽅法中添加⼀个参数(id),将⽅法中的参数,传给SQL语句 使⽤ #{} 的⽅式获取⽅法中的参数
  • #{id} 是一个占位符,表示 id 变量的值将在运行时替换进来

1 @Select("select username, `password`, age, gender, phone from userinfo where
id= #{id} ")
2 UserInfo queryById (Integer id);

 如果mapper接⼝⽅法形参只有⼀个普通类型的参数,#{…} ⾥⾯的属性名可以随便写,如:#{id}、# {value}。建议和参数名保持⼀致

添加测试⽤例

1 @Test
2 void queryById () {
3 UserInfo userInfo = userInfoMapper.queryById( 4 );
4 System.out.println(userInfo);
5 }

3.3 增(Insert) 

  insert into userinfo (username, `password`, age, gender, phone) values
("zhaoliu","zhaoliu", 19 , 1 ,"18700001234")
把SQL中的常量替换为动态的参数
Mapper接⼝
@Insert("insert into userinfo (username, `password`, age, gender, phone)
values (#{username},#{password},#{age},#{gender},#{phone})")
Integer insert (UserInfo userInfo);
直接使⽤UserInfo对象的属性名来获取参数
测试代码:
1 @Test
2 void insert () {
3 UserInfo userInfo = new UserInfo ();
4 userInfo.setUsername( "zhaoliu" );
5 userInfo.setPassword( "zhaoliu" );
6 userInfo.setGender( 2 );
7 userInfo.setAge( 21 );
8 userInfo.setPhone( "18612340005" );
9 userInfoMapper.insert(userInfo);
10 }
返回主键: 如果想要拿到⾃增id, 需要在Mapper接⼝的⽅法上添加⼀个Options的注解
  @Options(useGeneratedKeys = true, keyProperty = "id")
  @Insert("insert into userinfo (username, age, gender, phone) values
(# {userinfo.username},#{userinfo.age},#{userinfo.gender},#{userinfo.phone})")
Integer insert ( @Param("userinfo") UserInfo userInfo);
useGeneratedKeys:这会令 MyBatis 使⽤ JDBC 的 getGeneratedKeys ⽅法来取出由数据库内
部⽣成的主键(⽐如:像 MySQL 和 SQL Server 这样的关系型数据库管理系统的⾃动递增字
段),默认值:false.
keyProperty:指定能够唯⼀识别对象的属性,MyBatis 会使⽤ getGeneratedKeys 的返回值或
insert 语句的 selectKey ⼦元素设置它的值,默认值:未设置(unset)

 

测试数据:
1 @Test
2 void insert () {
3 UserInfo userInfo = new UserInfo ();
4 userInfo.setUsername( "zhaoliu" );
5 userInfo.setPassword( "zhaoliu" );
6 userInfo.setGender( 2 );
7 userInfo.setAge( 21 );
8 userInfo.setPhone( "18612340005" );
9 Integer count = userInfoMapper.insert(userInfo);
10 System.out.println( " 添加数据条数 :" +count + ", 数据 ID:" + userInfo.getId());
11 }

3.4 删(Delete)  

@Delete("delete from userinfo where id = #{id}")
void delete (Integer id);

3.5 改(Update) 

1 @Update("update userinfo set username=#{username} where id=#{id}")
2 void update (UserInfo userInfo);

3.6 查(Select)  

1 @Select("select id, username, `password`, age, gender, phone, delete_flag,
create_time, update_time from userinfo")
2 List<UserInfo> queryAllUser ();

 

从运⾏结果上可以看到, 我们SQL语句中, 查询了delete_flag, create_time, update_time, 但是这⼏个 属性却没有赋值.
原因:
当⾃动映射查询结果时,MyBatis 会获取结果中返回的列名并在 Java 类中查找相同名字的属性(忽略 ⼤⼩写)。 这意味着如果发现了 ID 列和 id 属性,MyBatis 会将列 ID 的值赋给 id 属性
解决办法:
1. 起别名
2. 结果映射
3. 开启驼峰命名

3.6.1 起别名

在SQL语句中,给列名起别名,保持别名和实体类属性名⼀样
  @Select("select id, username, `password`, age, gender, phone, delete_flag as
deleteFlag, " + "create_time as createTime, update_time as updateTime from userinfo")
public List<UserInfo> queryAllUser ();

PS:SQL语句太⻓时, 使⽤加号 + 进⾏字符串拼接

3.6.2 结果映射

1 @Select("select id, username, `password`, age, gender, phone, delete_flag,
create_time, update_time from userinfo")
2 @Results({
3                 @Result(column = "delete_flag",property = "deleteFlag"),
4                 @Result(column = "create_time",property = "createTime"),
5                 @Result(column = "update_time",property = "updateTime")
6 })
7 List<UserInfo> queryAllUser ();
  • column 属性:指定数据库查询结果集中的列名。
  • property 属性:指定 Java 对象中的属性名,这个属性会接收 column 属性指定的列的值。

 如果其他SQL, 也希望可以复⽤这个映射关系, 可以给这个Results定义⼀个名称

3.6.3 开启驼峰命名(推荐)

  • 通常数据库列使⽤蛇形命名法进⾏命名(下划线分割各个单词), ⽽ Java 属性⼀般遵循驼峰命名法约定.
  • 为了在这两种命名⽅式之间启⽤⾃动映射,需要将 mapUnderscoreToCamelCase 设置为 true。
  • 驼峰命名规则: abc_xyz => abcXyz
    表中字段名:abc_xyz
    类中属性名:abcXyz

4. MyBatis XML配置⽂件

Mybatis的开发有两种⽅式:
        1. 注解
        2. XML
  • 使⽤Mybatis的注解⽅式,主要是来完成⼀些简单的增删改查功能. 如果需要实现复杂的SQL功能,建 议使⽤XML来配置映射语句,也就是将SQL语句写在XML配置⽂件中
  • MyBatis XML的⽅式需要以下两步
                1. 配置数据库连接字符串和MyBatis
                2. 写持久层代码

4.1 配置连接字符串和MyBatis

application.yml⽂件, 配置内容如下:
1 # 数据库连接配置
2 spring:
3 datasource:
4 url: jdbc:mysql://127.0.0.1:3306/mybatis_test?
characterEncoding=utf8&useSSL=false
5 username: root
6 password: root
7 driver-class-name: com.mysql.cj.jdbc.Driver
8 # 配置 mybatis xml 的⽂件路径,在 resources/mapper 创建所有表的 xml ⽂件
9 mybatis:
10 mapper-locations: classpath:mapper/**Mapper.xml

 4.2 写持久层代码

1. ⽅法定义 Interface
2. ⽅法实现: XXX.xml

4.2.1 添加 mapper 接⼝

@Mapper
  public interface UserInfoXMlMapper {
 List<UserInfo> queryAllUser ();
  }

MyBatis 的固定 xml 格式:

1 <?xml version= "1.0" encoding= "UTF-8" ?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
3 < mapper namespace = "com.example.demo.mapper.UserInfoMapper" >
4
5 </ mapper >

 

 具体实现:

1 <?xml version= "1.0" encoding= "UTF-8" ?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
3 < mapper namespace = "com.example.demo.mapper.UserInfoXMlMapper" >
4 < select id = "queryAllUser" resultType = "com.example.demo.model.UserInfo" >
5 select username,`password`, age, gender, phone from userinfo
6 </ select >
7 </ mapper >

 

<mapper> 标签:需要指定 namespace 属性,表⽰命名空间,值为 mapper 接⼝的全限定
名,包括全包名.类名。
<select> 查询标签:是⽤来执⾏数据库的查询操作的:
id :是和 Interface (接⼝)中定义的⽅法名称⼀样的,表⽰对接⼝的具体实现⽅法。
resultType :是返回的数据类型,也就是开头我们定义的实体类

4.3 增删改查操作

4.3.1 增(Insert)

UserInfoMapper接⼝:
Integer insertUser (UserInfo userInfo);
UserInfoMapper.xml实现:
< insert id = "insertUser" >
insert into userinfo (username, `password`, age, gender, phone) values (#
{username}, #{password}, #{age},#{gender},#{phone})
  </ insert >

4.3.2 删(Delete) 

UserInfoMapper接⼝:
Integer deleteUser (Integer id);

UserInfoMapper.xml实现:

1 < delete id = "deleteUser" >
2 delete from userinfo where id = #{id}
3 </ delete >

 

4.3.3 改(Update)  

UserInfoMapper接⼝:
Integer updateUser (UserInfo userInfo);

UserInfoMapper.xml实现

 

< update id = "updateUser" >
 update userinfo set username=#{username} where id=#{id}
</ update >

4.3.4 查(Select)  

1 < select id = "queryAllUser" resultType = "com.example.demo.model.UserInfo" >
2 select id, username,`password`, age, gender, phone, delete_flag,
create_time, update_time from userinfo
3 </ select >

5. 其他查询操作

5.1 多表查询

多表查询和单表查询类似, 只是SQL不同⽽已

5.1.1 准备⼯作

上⾯建了⼀张⽤⼾表, 我们再来建⼀张⽂章表, 进⾏多表关联查询. ⽂章表的uid, 对应⽤⼾表的id.

 (表就不展示了,看代码理解代码即可)

5.1.2 数据查询

需求: 根据uid查询作者的名称等相关信息
1 SELECT
2 ta.id,
3 ta.title,
4 ta.content,
5 ta.uid,
6 tb.username,
7 tb.age, 8 tb.gender
9 FROM
10 articleinfo ta
11 LEFT JOIN userinfo tb ON ta.uid = tb.id
12 WHERE
13 ta.id = 1

接⼝定义:

1 import com.example.demo.model.ArticleInfo;
2 import org.apache.ibatis.annotations.Mapper;
3
4 @Mapper
5 public interface ArticleInfoMapper {
6
7 @Select("SELECT
ta.id,ta.title,ta.content,ta.uid,tb.username,tb.age,tb.gender " +
8 "FROM articleinfo ta LEFT JOIN userinfo tb ON ta.uid = tb.id " +
9 "WHERE ta.id = #{id}")
10 ArticleInfo queryUserByUid (Integer id);
11 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值