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

相关推荐
YL20040426几秒前
035LRU缓存
java·leetcode·缓存
不像程序员的程序媛17 分钟前
mysql 0000-00-00 00:00:00零日期问题
java·mysql
霸道流氓气质22 分钟前
Spring @Scheduled 单线程陷阱:当设备重连阻塞了整个定时任务体系
java·spring boot·spring
DFT计算杂谈27 分钟前
AMSET 设置多核并行计算
java·前端·css·html·css3
Gerardisite44 分钟前
CRM、ERP、OA 如何连接企业微信?QiWe 提供标准化解决方案
java·python·机器人·自动化·企业微信
城管不管1 小时前
Maven Helper
java·macos·intellij-idea
ch.ju1 小时前
Java程序设计(第3版)第三章——数组的动态获取
java·开发语言
Java知识技术分享1 小时前
策略模式的两种实现:抽象类和接口
java·spring·策略模式
液态不合群1 小时前
Redis--哨兵机制与CAP定理
java·redis·bootstrap
曹牧1 小时前
Java:PDF文件扁平化处理
java·开发语言·pdf