SpringBoot与Mybatis集成

    |     2017年6月16日   |   springboot   |     0 条评论   |    1280

一、SpringBoot与Mybatis集成步骤如下

1. 引入mybatis-spring-boot相关依赖

<!-- mybatis/spring包 -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.2.0</version>
</dependency>

<!-- mysql数据驱动 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

2. 实现mybaits相关Bean类,接口和映射文件(可用插件生成)

mybaits

3. 在application.yml文件中添加数据源和mybaits映射文件扫描配置

 spring:
  mvc:
    view:
     prefix: /WEB-INF/views/
     suffix: .jsp
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf8&useSSL=true
    username: root
    password: b123
mybatis:
  mapper-locations: classpath:com/ittx/java1608/sbdemo2/mapping/*.xml

# springboot中配置mybaits日志输出
logging: 
    level:
        com.ittx.java1608.sbdemo2.dao: TRACE

4. 编写工具类实现sqlSessionFactory和mybatis接口扫描

/**
 * MyBatis扫描接口
 *  <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.ittx.java1608.sbdemo2.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>
 */
@Configuration
public class MyBatisMapperScannerConfig {

	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer() {
		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
		mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
		mapperScannerConfigurer.setBasePackage("com.ittx.java1608.sbdemo2.dao");
		return mapperScannerConfigurer;
	}
}

5. 经过以上配置springboot已成功集成mybatis.编写测试LoginController实现登录

@Controller
public class LoginController {
	@Autowired
	private UserMapper userMapper;

	@RequestMapping("/login")
	public String login(){
		return "login";
	}

	@RequestMapping("/login_submit")
	public String loginSubmit(String username,String password,Model model){
		User user = userMapper.checkLogin(username, password);
		if(user != null){
			model.addAttribute("message", "登录成功!");
		}else{
			model.addAttribute("message", "用户名或密码错误!");
		}
		return "login";
	}
}
转载请注明来源:SpringBoot与Mybatis集成
本文链接地址:http://it.warmtel.com/?p=2001
回复 取消