SpringBoot项目整合mybatis的方法步骤与实例
1. 导入依赖的jar包
创新互联建站的客户来自各行各业,为了共同目标,我们在工作上密切配合,从创业型小企业到企事业单位,感谢他们对我们的要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。专业领域包括做网站、成都做网站、电商网站开发、微信营销、系统平台开发。
springboot项目整合mybatis之前首先要导入依赖的jar包,配置pom.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>4.0.0 com.u springboot-mybatis 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 1.3.0.RELEASE com.us.Application 3.2.7 1.2.2 1.8 1.8 org.springframework.boot spring-boot-starter-web MySQL mysql-connector-java 6.0.5 com.mchange c3p0 0.9.5.2 commons-logging commons-logging org.springframework spring-jdbc org.mybatis mybatis ${mybatis.version} org.mybatis mybatis-spring ${mybatis-spring.version} org.apache.commons commons-lang3 3.4
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 ListgetList(Map 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(Mapmap) { 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) { Mapmap = CommonUtil.getParameterMap(request); return new ResponseEntity
然后在启动入口类中扫描定义的这些配置累(配置包名可却省只写部分包名)如下:
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); } } }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对创新互联的支持。如果你想了解更多相关内容请查看下面相关链接
当前标题:SpringBoot项目整合mybatis的方法步骤与实例
文章出自:http://pwwzsj.com/article/gjscpi.html