SpringBoot项目整合mybatis的方法步骤与实例
1. 导入依赖的jar包
springboot项目整合mybatis之前首先要导入依赖的jar包,配置pom.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.u</groupId> <artifactId>springboot-mybatis</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.0.RELEASE</version> </parent> <properties> <start-class>com.us.Application</start-class> <mybatis.version>3.2.7</mybatis.version> <mybatis-spring.version>1.2.2</mybatis-spring.version> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> </properties> <dependencies> <!--springboot--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--db--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <!--mybatis--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!--util--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> </dependencies> </project>
2. 配置数据源
pom.xml配置完毕后需要配置数据源了。新建DBConfig类配置数据源,代码如下:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import com.alibaba.druid.pool.DruidDataSource; import com.google.common.base.Preconditions; @Configuration public class DBConfig { @Autowired private Environment env; @Bean(name = "dataSource") public DruidDataSource dataSource() { final String url = Preconditions.checkNotNull(env.getProperty("ms.db.url")); final String username = Preconditions.checkNotNull(env.getProperty("ms.db.username")); final String password = env.getProperty("ms.db.password"); final int maxActive = Integer.parseInt(env.getProperty("ms.db.maxActive", "200")); DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setMaxActive(maxActive); return dataSource; } }
3. 添加数据库连接信息
在配置文件application.properties中添加数据库连接信息如下:
ms.db.url=jdbc:mysql://localhost:3306/dev?prepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&characterEncoding=utf-8&allowMultiQueries=true ms.db.username=root ms.db.password=admin ms.db.maxActive=500
4. 配置mybatis的SqlSessionFactoryBean
数据源配置完以后要配置mybatis的SqlSessionFactoryBean进行扫描mapper,新建MyBatisConfig类代码如下(classpath*:mapper/*.xml为mapper.xml文件路径):
import javax.sql.DataSource; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyBatisConfig { @Autowired private DataSource dataSource; @Bean(name = "sqlSessionFactory") public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext applicationContext) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.setMapperLocations(applicationContext.getResources("classpath*:mapper/*.xml")); return sessionFactory; } }
5. 配置MapperScannerConfigurer扫描dao层
然后配置MapperScannerConfigurer扫描dao层,新建类MyBatisScannerConfig代码如下(注意与MyBatisConfig不要写在一个类里):
import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyBatisScannerConfig { @Bean public MapperScannerConfigurer MapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setBasePackage("com.example.*.dao"); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); return mapperScannerConfigurer; } }
6. 开启数据库事务(必须)代码如下
import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.TransactionManagementConfigurer; @Configuration public class TransactionConfig implements TransactionManagementConfigurer{ @Autowired private DataSource dataSource; @Bean(name = "transactionManager") @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } }
7. 实战
配置大致就是如此,然后就是新建java bean(省略,文章底部有源码地址)
新建mapper.xml文件(省略,文章底部有源码地址,关于mapper.xml 文件编写的疑问可以看我以前的springmvc+mybatis 系列文章)
新建dao层。代码如下:
import java.util.List; import java.util.Map; import com.example.base.model.User; import com.example.config.MyBatisRepository; public interface UserDao { public List<User> getList(Map<String,Object> map); }
service层要在实现类上添加@service注解,代码如下:
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.base.dao.UserDao; import com.example.base.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public Object getList(Map<String, Object> map) { return userDao.getList(map); } }
controller层也要加@controller注解代码如下:
import javax.servlet.http.HttpServletRequest; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.example.base.service.UserService; import com.example.base.util.CommonUtil; import com.example.demo.ServiceEmail; @Controller @RequestMapping(value = "/users") public class UserController { @Autowired private UserService userService; @Autowired private ServiceEmail serviceEmail; /*** * api :localhost:8099/users?id=99 localhost:8099/users * * @param request * @return */ @RequestMapping(method = RequestMethod.GET, produces = "application/json;charset=UTF-8") @ResponseBody public ResponseEntity<?> list(HttpServletRequest request) { Map<String, Object> map = CommonUtil.getParameterMap(request); return new ResponseEntity<Object>(userService.getList(map), HttpStatus.OK); } }
然后在启动入口类中扫描定义的这些配置累(配置包名可却省只写部分包名)如下:
import java.util.Arrays; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; @ComponentScan(basePackages ="com.example") @SpringBootApplication public class Application extends SpringBootServletInitializer{ @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) throws Exception { ApplicationContext ctx = SpringApplication.run(Application.class, args); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.println(beanName); } } }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。如果你想了解更多相关内容请查看下面相关链接