一.spring boot內建Mybatis
gradle配置:
//gradle配置:
compile("org.springframework.boot:spring-boot-starter-web:1.4.2.RELEASE")
compile ('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0'){
exclude group:'org.springframework'
}
compile("mysql:mysql-connector-java:5.1.39")
application.yml配置
spring:
profiles:
active: local
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
cache-enabled: true
mapper-locations: classpath:mapper/*.xml
application-local.yml配置
spring:
datasource:
username: root
password:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/house?characterEncoding=utf8
server:
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.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.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(basePackages = "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());
}
}
}