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

相关推荐
NE_STOP7 小时前
MyBatis-配置文件解读及MyBatis为何不用编写Mapper接口的实现类
java
后端AI实验室12 小时前
用AI写代码,我差点把漏洞发上线:血泪总结的10个教训
java·ai
程序员清风14 小时前
小红书二面:Spring Boot的单例模式是如何实现的?
java·后端·面试
belhomme14 小时前
(面试题)Redis实现 IP 维度滑动窗口限流实践
java·面试
Be_Better14 小时前
学会与虚拟机对话---ASM
java
开源之眼16 小时前
《github star 加星 Taimili.com 艾米莉 》为什么Java里面,Service 层不直接返回 Result 对象?
java·后端·github
Maori31617 小时前
放弃 SDKMAN!在 Garuda Linux + Fish 环境下的优雅 Java 管理指南
java
用户9083246027317 小时前
Spring AI 1.1.2 + Neo4j:用知识图谱增强 RAG 检索(上篇:图谱构建)
java·spring boot
小王和八蛋18 小时前
DecimalFormat 与 BigDecimal
java·后端
beata18 小时前
Java基础-16:Java内置锁的四种状态及其转换机制详解-从无锁到重量级锁的进化与优化指南
java·后端