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.启动测试类

相关推荐
leikooo20 分钟前
ARTS 0913: 双栈互补实现队列、CIDR 聚合化解路由膨胀与 AI 作弊串通绝非偶然 Bug
java·链表·个人开发
星间都市山脉33 分钟前
Android16 SystemService.onBootPhase 调用时机
android·java·linux·windows·ubuntu
深入云栈38 分钟前
Netty 4.2.x 源码深度解析 (十三):Epoll 传输 —— Linux 高性能 IO 的 Netty 实现
java·后端
ynchyong39 分钟前
Linux nohup 后台服务合并标准错误输出到一个文件
java·linux·运维
用户31268748772041 分钟前
Lombok 的 @Data 到底怎么工作的?Java 注解处理器实战全链路拆解
java
小羊没烦恼!1 小时前
Memory 记忆设计讨论:为什么 Agent Memory 不能只靠向量数据库?
java·开发语言·windows·算法·c#
天远API1 小时前
零信任架构实战:基于天远单人婚姻查询构建自动化联合贷款审计网关
java·人工智能·架构·自动化
九皇叔叔1 小时前
从本地事务到分布式事务
java·分布式·分布式事务·cap·base
黑马程序员毕设2 小时前
基于微信小程序的节目活动报名与管理系统设计与实现
java·开发语言·spring boot·后端·电脑
小坏讲微服务2 小时前
Spring AI 高频面试题20道
java·spring·ai·agent·springai