首页 > 网站 > WEB开发 > 正文

spring boot 整合mybatis

2024-04-27 15:03:40
字体:
来源:转载
供稿:网友

目录

目录sPRing boot 整合mybatispomxml依赖applicationproperties配置使用MyBatis

本篇所有代码均来翟永超的博客: - 本文仅供自己学习之用

spring boot 整合mybatis

工作中所使用的框架spring boot + mybatis工作之余看到了搭建方法,顺便把它放到这里,以供以后参考

pom.xml依赖

在pom.xml引入所需要的依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>MySQL</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> </dependencies>

application.properties配置

在application.properties中配置mysql的连接配置spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.passWord=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver

使用MyBatis

在Mysql中创建User表,包含id(BIGINT)、name(INT)、age(VARCHAR)字段。同时,创建映射对象Userpublic class User { private Long id; private String name; private Integer age; // 省略getter和setter}创建User映射的操作UserMapper,为了后续单元测试验证,实现插入和查询操作@Mapperpublic interface UserMapper { @Select("SELECT * FROM USER WHERE NAME = #{name}") User findByName(@Param("name") String name); @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") int insert(@Param("name") String name, @Param("age") Integer age);}创建Spring Boot主类@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}创建单元测试 测试逻辑:插入一条name=AAA,age=20的记录,然后根据name=AAA查询,并判断age是否为20测试结束回滚数据,保证测试单元每次运行的数据环境独立@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = Application.class)@Transactionalpublic class ApplicationTests { @Autowired private UserMapper userMapper; @Test @Rollback public void findByName() throws Exception { userMapper.insert("AAA", 20); User u = userMapper.findByName("AAA"); Assert.assertEquals(20, u.getAge().intValue()); }}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表