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

相关推荐
金銀銅鐵9 小时前
为什么枚举类中可以定义抽象方法
java·后端·ai编程
文丑颜不良啊10 小时前
LeetCode1941~1960题目解析
java·leetcode
txxzjmzlh11 小时前
SpringBoot 统⼀功能处理
java·spring boot·后端
nice_lcj52012 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
码农小河6613 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql
SL_staff14 小时前
从配置失效到逻辑复用:JVS-Logic 如何构建可治理的业务编排中枢
java·spring·产品
特立独行的猫A14 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
文丑颜不良啊15 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊15 小时前
LeetCode2001~2020题目解析
java·leetcode
用户37215742613515 小时前
Java 批量提取 Word 文档中的图片并保存到本地
java