Springboot整合mybatis注解版

1.引入 MyBatis Starter 依赖

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

2.数据库建表(tx_person)

3.创建实体类Person

private int pid; private String pname; private String addr; private int gender; private Date birth;

4.创建mapper

@Mapper public interface PersonMapper { @Select("select * from tx_person") List<Person> getPersons(); @Select("select * from tx_person where pid = #{id}") Person getPersonById(int id); @Options(useGeneratedKeys = true, keyProperty = "pid") @Insert("insert into tx_person(pid, pname, addr, gender, birth) " + "values(#{pid}, #{pname}, #{addr}, #{gender}, #{birth})") void insert(Person person); @Delete("delete from tx_person where pid = #{id}") void update(int id); }

5.解决驼峰 & 下划线映射问题

创建MybatisConfig

@Configuration

public class MybatisConfig {

@Configuration public class MybatisConfig { @Bean public ConfigurationCustomizer getCustomizer() { return new ConfigurationCustomizer() { @Override public void customize(org.apache.ibatis.session.Configuration configuration) { configuration.setMapUnderscoreToCamelCase(true); } }; } }

6.创建测试类SpringBootMybatisTest

@SpringBootTest @RunWith(SpringRunner.class) public class SpringbootMybatisTest { @Autowired TxPersonMapper txPersonMapper; @Autowired ApplicationContext context; @Test public void contextLoads() { DataSource bean = context.getBean(DataSource.class); System.out.println(bean); } @Test public void testMybatis() { TxPerson p = txPersonMapper.getPersonById(1); System.out.println(p); } }

7.启动测试类

相关推荐
苏瞳儿1 天前
java对数据库的增删改查
java·数据库·oracle
zhangjw341 天前
Java基础语法:变量、数据类型与运算符,从原理到实战
java·开发语言
yaoxin5211231 天前
384. Java IO API - Java 文件复制工具:Copy 示例完整解析
java·开发语言·python
NotFound4861 天前
实战指南如何实现Java Web 拦截机制:Filter 与 Interceptor 深度分享
java·开发语言·前端
一 乐1 天前
医院挂号|基于springboot + vue医院挂号管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·医院挂号管理系统
鱼鳞_1 天前
Java学习笔记_Day29(异常)
java·笔记·学习
烟锁池塘柳01 天前
一文讲透 C++ / Java 中方法重载(Overload)与方法重写(Override)在调用时机等方面的区别
java·c++·面向对象
一叶飘零_sweeeet1 天前
深入拆解 Fork/Join 框架:核心原理、分治模型与参数调优实战
java·并发编程
云烟成雨TD1 天前
Spring AI Alibaba 1.x 系列【23】短期记忆
java·人工智能·spring
摇滚侠1 天前
帮我整理一份 IDEA 开发中常用快捷键
java·ide·intellij-idea