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拼接字符串

相关推荐
繁花与尘埃1 小时前
HTML5简介与基本骨架(本文为个人学习笔记,内容整理自哔哩哔哩UP主【非学者勿扰】的公开课程。 > 所有知识点归属原作者,仅作非商业用途分享)
笔记·学习·html5
东方芷兰1 小时前
LLM 笔记 —— 04 为什么语言模型用文字接龙,图片模型不用像素接龙呢?
人工智能·笔记·深度学习·语言模型·自然语言处理
Rock_yzh2 小时前
AI学习日记——卷积神经网络(CNN):完整实现与可视化分析
人工智能·python·深度学习·神经网络·学习·cnn
Test.X3 小时前
学习16天:pytest学习
学习·pytest
XISHI_TIANLAN3 小时前
【多模态学习】Q&A6: 什么是MOE架构?Router Z Loss函数是指什么?负载均衡损失(Load Balancing Loss)又是什么?
学习·算法·语言模型
Diligence8154 小时前
计算机网络学习总结(二)应用层
学习·计算机网络
小墨宝4 小时前
web前端学习LangGraph
前端·学习
memorycx4 小时前
听课笔记CSAPP
笔记
尘似鹤5 小时前
微信小程序学习(五)
学习·微信小程序·小程序
计算机毕业设计小帅5 小时前
【2026计算机毕业设计】基于微信小程序的英语在线学习系统
学习·微信小程序·毕业设计·课程设计