MyBatis的基础操作

目录

一.什么是MyBatis?

二.使用MyBatis的准备工作

1.引入依赖:

2.配置数据库连接字符串(建立MaBatis和MySQL的连接)

3.在model包中建立数据库对应的实体类UserInfo

三.通过@注解的方式实现MyBatis的开发

1.插入语句(Insert)

2.删除语句(Delete)

3.更新语句(Update)

4.查询语句(Select) 

1.起别名:

2.结果映射:

3.开启驼峰命名:

四.通过xml的方式实现MyBatis的开发

1.前提准备:

1)添加关于xml的配置(yml)

2)在resources文件夹中添加xml文件,在文件写入固定格式

3)接着就可以在里写数据库语句了

2.插入语句(Insert)

3.删除语句(Delete)

4.更新语句(Update)

5.查询语句(Select)


一.什么是MyBatis?

MyBatis是一个开源的持久层框架,它提供了一种优雅的方式来管理数据库访问代码。MyBatis通过将SQL语句映射到Java方法,使得在Java应用程序中执行数据库操作变得更加简单和直观。

MyBatis的核心思想是将SQL语句与Java方法和参数进行绑定,这样可以避免传统的JDBC编程中的大量样板代码。开发人员可以使用XML或注解来定义SQL映射,将SQL语句保存在外部文件中,并将其与Java接口或类进行绑定。


二.使用MyBatis的准备工作

1.引入依赖:

        <dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.3.1</version>
		</dependency>

		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>

2.配置数据库连接字符串(建立MaBatis和MySQL的连接)

spring:
 datasource:
   url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
   username: root
   password: root
   driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
 configuration: # 配置打印 MyBatis⽇志
   map-underscore-to-camel-case: true #配置驼峰⾃动转换
   log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3.在model包中建立数据库对应的实体类UserInfo

public class UserInfo {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private Integer gender;
    private String phone;
    private Integer deleteFlag;
    private Date createTime;
    private Date updateTime;
}

前提工作做完后,就可以实现数据库操作了


三.通过@注解的方式实现MyBatis的开发

1.插入语句(Insert)

使用@Insert("")注解,并在("")中实现插入语句

示例:

@Insert("insert into userinfo (username, password, age, gender, phone) " +
            "values (#{userInfo.username},#{userInfo.password},#{userInfo.age}," +
            "#{userInfo.gender},#{userInfo.phone})")
    Integer insertUserInfo(UserInfo userInfo);

//在上述代码中实现了插入一个userInfo对象的信息到数据库中userinfo的表中
//userInfo的属性不能直接写到sql语句中,而是通过#{userInfo.属性字段}来自动查找userInfo的属性并填入sql语句中

同时可以搭配@Param注解使用,为方法中的参数指定名称

@Insert("insert into userinfo (username, password, age, gender, phone) " +
            "values (#{user.username}, #{user.password}, #{user.age}," +
            "#{user.gender}, #{user.phone})")
    Integer insertUserInfo2(@Param("user") UserInfo userInfo);
    
    //将userInfo识别成user使用
    

当传入参数有多个时,会按顺序填入各属性,而使用@Param就可以更自由的使用参数,同时可以提高代码的清晰度和可读性

Insert 语句默认返回的是受影响的行数,如果想要拿到⾃增id, 需要在方法上添加⼀个@Options注解

    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into userinfo (username, password, age, gender, phone) " +
            "values (#{user.username}, #{user.password}, #{user.age}," +
            "#{user.gender}, #{user.phone})")
    Integer insertUserInfo2(@Param("user") UserInfo userInfo);
  • useGeneratedKeys = true表示告诉 MyBatis 在执行插入操作后要生成主键。当这个参数设置为 true 时,MyBatis 会通知数据库生成主键,并将生成的主键值返回给应用程序。

  • keyProperty = "id"表示指定将生成的主键值设置到对象的哪个属性上。在这里,keyProperty 指定了要将生成的主键值设置到对象的 id 属性上。

示例:

UserInfo newUser = new UserInfo();
newUser.setUsername("testUser");
newUser.setPassword("123456");
newUser.setAge(25);
newUser.setGender("male");
newUser.setPhone("123456789");

Integer result = insertUserInfo2(newUser);

System.out.println("插入成功,生成的主键值为:" + newUser.getId());

//返回的主键值自动设置到newUser的id属性上了
//⽅法返回值result依然是受影响的⾏数

2.删除语句(Delete)

使用@Delete("")注解,并在("")中实现删除语句

示例:

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

//通过id删除某个用户

 同样可以使用@Param注解 

3.更新语句(Update)

使用@Update("")注解,并在("")中实现更新语句

示例:

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

//通过id更新用户的姓名

4.查询语句(Select) 

使用@Select("")注解,并在("")中实现查询语句

示例:

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

MyBatis会自动将查询出的表的数据按照字段名依次放入List<UserInfo> 对象中

但是,如果表的字段名类的属性不一致时,就无法正常赋值了,例如表中的create_time字段类的createTime属性

解决办法:

1.起别名:
@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> queryAllUser2();


//查询语句中 as 加上想改成的名字
2.结果映射:
@Select("select id, username, `password`, age, gender, phone, delete_flag, 
create_time, update_time from userinfo")
@Results({
 @Result(column = "delete_flag",property = "deleteFlag"),
 @Result(column = "create_time",property = "createTime"),
 @Result(column = "update_time",property = "updateTime")
})
List<UserInfo> queryAllUser();
3.开启驼峰命名:

在yml配置中加上:

mybatis:
 configuration:
 map-underscore-to-camel-case: true #配置驼峰⾃动转换

到此关于注解实现MyBatis的方式就结束了~


四.通过xml的方式实现MyBatis的开发

1.前提准备:

1)添加关于xml的配置(yml)
mybatis:
 mapper-locations: classpath:mapper/**Mapper.xml
2)在resources文件夹中添加xml文件,在文件写入固定格式

<?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.example.demo.mapper.UserInfoMapper">
   //写MySQL语句
</mapper>
3)接着就可以在<mapper></mapper>里写数据库语句了

2.插入语句(Insert)

使用<insert>标签实现插入语句

<mapper namespace="com.example.demo.mapper.UserInfoMapper">
    <insert id="insertUser">
        insert into userinfo (username, password, age, gender, phone) values (#
        {username}, #{password}, #{age},#{gender},#{phone})
    </insert>

</mapper>

sql语句基本没有变化,只是放入了<insert>标签以及用id指定了mapper中要实现的接口的方法名

如果要返回自增 id,则需要设置useGeneratedKeys 和keyProperty属性

<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
 insert into userinfo (username, `password`, age, gender, phone) values
 (#{userinfo.username},#{userinfo.password},#{userinfo.age},#
{userinfo.gender},#{userinfo.phone})
</insert>

3.删除语句(Delete)

使用<delete>标签实现删除语句

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

4.更新语句(Update)

使用<update>标签实现更新语句

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

5.查询语句(Select)

使用<select>标签实现查询语句

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

同理,如果表的字段名类的属性不一致时,就无法正常赋值了,解决方法和用注解的方式类似


到这里,有关MyBatis的基础操作的介绍就全部讲完了

  • 12
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值