web开发学习笔记(13.mybatis基于注解配置)

1.使用mybatis基本步骤

2.引入依赖

<!--        mysql-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>
<!--        mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
<!--        测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

3.配置application.properties 配置数据库连接信息

#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url,test为数据库名称
spring.datasource.url=jdbc:mysql://localhost:3306/test
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=123456

4.编写实体类和接口

5.编写测试类

@SpringBootTest    //单元测试注解类
public class applicationtest {

    @Autowired
    private UserMapper userMapper;


    @Test
    public void test() {
        List<User> userList = userMapper.list();
        System.out.println(userList.get(0).getName());
    }


}

6.或者使用stream流的方式进行输出

7.设置查看mapper层里的提示信息,方便操作

  1. 使用jdbc连接数据库

9.数据库连接池

10.lombok,在编译时,会自动生成对应的java代码

之前的实体类过于臃肿

使用lombok自动生成以下内容,简化开发,提高效率

11.引入lombok依赖,不需要指定版本号,因为springboot parent父项目中已经制定了版本

<!--        lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

12.lombok使用方法

13.数据库字段中含有_下划线的,在实体类中要用驼峰命名

14.删除操作,使用#{id}作为占位符

15mybatis日志输出到控制台

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

16.下面这种是预编译的sql,性能更高,更安全(防止sql注入)

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

17.有两种参数占位符

第一种较好

18.新增操作

在mapper中添加

在测试类中添加

19.主键返回,会把新插入的内容中的主键作为返回值

20.更新操作

在mapper中添加

在测试类中添加

21.根据id查询员工

mapper中添加

测试类中添加

22.数据封装

解决方法1:给字段起别名

解决方案2:手动封装

解决方案3:开启驼峰命名自动开关

#开启mybayis驼峰命名自动开关
mybatis.configuration.map-underscore-to-camel-case=true

24.条件查询员工

25.使用concat拼接字符串

相关推荐
Willliam_william17 分钟前
SystemC学习(1)— SystemC安装与HelloWorld
学习
sealaugh3222 分钟前
aws(学习笔记第一课) AWS CLI,创建ec2 server以及drawio进行aws画图
笔记·学习·aws
布丁不叮早起枣祈22 分钟前
10.5学习
学习
CXDNW25 分钟前
【网络篇】计算机网络——应用层详述(笔记)
服务器·笔记·计算机网络·http·web·cdn·dns
向上的车轮31 分钟前
Django学习笔记五:templates使用详解
笔记·学习·django
看山还是山,看水还是。1 小时前
MySQL 管理
数据库·笔记·mysql·adb
蒲公英10012 小时前
vue3学习:axios输入城市名称查询该城市天气
前端·vue.js·学习
训山2 小时前
【11】纯血鸿蒙HarmonyOS NEXT星河版开发0基础学习笔记-模块化语法与自定义组件
笔记·学习·华为·harmonyos·鸿蒙系统
①个程序员2 小时前
thinkphp 学习记录
学习
alfiy3 小时前
Elasticsearch学习笔记(四) Elasticsearch集群安全配置一
笔记·学习·elasticsearch