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

相关推荐
qq_452396231 小时前
第三篇:Transactional Outbox 模式详解
java·kubernetes·rocketmq
3095566662 小时前
股票接口重试怎么分类:正常、空数组与错误响应的幂等处理
java·大数据·开发语言·数据库·php·api接口·股票数据api接口
摇滚侠8 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 21
java·开发语言·笔记
雪芽蓝域zzs9 小时前
第15节:MyBatis-Plus 分页 + 条件查询(不带 Redis)
spring boot
凌冰_10 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
雪芽蓝域zzs10 小时前
第14章:SpringBoot3 + MyBatis‑Plus 基础 CRUD(无 Redis)
spring boot
Rain的Java大神之路11 小时前
Spring AI 2.0 GA 深度复盘:Java 后端做 AI 的分水岭,到底画在哪?
java·后端·aigc
如夏倾城13 小时前
进程状态模型详解:从三态、五态到 Linux 状态码映射
java·linux·服务器
小南家的青蛙14 小时前
JVM 参数调优实战指南
java·jvm