一.spring boot集成Mybatis

gradle配置:

//gradle配置: compile("org.spring work.boot:spring-boot-starter-web:1.4.2.RELEASE") compile ('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0'){        exclude group:'org.spring work'    } compile("mysql:mysql-connector-java:5.1.39")

application.yml配置

spring:    profiles:      active: localmybatis:      configuration:       log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl       cache-enabled: true         mapper-locations: classpath:mapper/*. 

application-local.yml配置

spring:    datasource:      username: root      password:      driver-class-name: com.mysql.jdbc.Driver      url: jdbc:mysql://localhost:3306/house?characterEncoding=utf8server:  port: 8082

注意此处配置文件最好在classpath的根目录下

三.spring-boot启动代码:

package com.lyhs.machineparts.run;import com.lyhs.machineparts.entity.User;import com.lyhs.machineparts.mapper.UserMapper;import org.mybatis.spring.annotation.MapperScan;import org.spring work.boot.SpringApplication;import org.spring work.boot.autoconfigure.SpringBootApplication;import org.spring work.context.ApplicationContext;import org.spring work.context.annotation.ComponentScan;import java.sql.SQLException;import java.util.List;/** * 1.注意@MapperScan注解必须在spring-boot处标注,作用是扫描Mapper接口并创建其代理对象,作用类似于MapperScannerConfigure * 2.spring-boot对象池自动将根据配置文件自动创建SqlSessionFactoryBean与SqlSessionTemplate对象 * 3.spring-boot的好处省略绝大多数代码及配置文件 * Created by niechen on 17/7/16. */@SpringBootApplication@ComponentScan("com.lyhs")@MapperScan( Packages = "com.lyhs.machineparts.mapper")public class PortalProvider {    public static void main(String[] args) throws SQLException {        ApplicationContext applicationContext = SpringApplication.run(PortalProvider.class, args);        UserMapper userMapper = applicationContext.getBean(UserMapper.class);        // System.out.println(houseMapper.toString());        List<User> users = userMapper.selectAll();        for (User user : users) {            System.out.println(user.getName());        }    }}

 

收藏 打印