1.POM文件配置
4.0.0
com.willow
springboot-mybatis
0.0.1-SNAPSHOT
jar
springboot-mybatis
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
1.5.10.RELEASE
UTF-8
UTF-8
1.8
com.alibaba
druid
1.1.8
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
2.yml文件配置
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.7.108/willow
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
# schema: #自动生成表sql list类型
# - classpath:sql/department.sql
# - classpath:sql/employee.sql
mybatis:
# 指定全局配置文件位置
#config-location: classpath:mybatis/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*.xml
3.druid数据源
package com.willow.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DriudConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid监控 访问 http://localhost:8080/druid/login.html
//配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){ //注册一个Servlet
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问IP
initParams.put("deny","192.168.15.21"); //拒绝访问的IP
bean.setInitParameters(initParams);
return bean;
}
//2.配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){//注册一个Filter
FilterRegistrationBean bean=new FilterRegistrationBean(new WebStatFilter());
Map initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*"); //排除的请求
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*")); //拦截的请求
return bean;
}
}
4.xml配置文件版本
INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
xml版本mapper文件
package com.willow.mapper;
import com.willow.entity.Employee;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
public Integer insertEmp(Employee employee) ;
}
5.注解版本mapper
package com.willow.mapper;
import com.willow.entity.Department;
import org.apache.ibatis.annotations.*;
//指定这是一个操作数据库的mapper
//@Mapper
public interface DepartmentMapper {
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);
@Delete("delete from department where id=#{id}")
public int deleteDeptById(Integer id);
@Options(useGeneratedKeys = true,keyProperty = "id") //自动生成的注解
@Insert("insert into department(department_name) values(#{departmentName})")
public int insertDept(Department department);
@Update("update department set department_name=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}
6.启动类
package com.willow;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.willow.mapper") //或者mapper类上添加Mapper注解
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
7.Controller
package com.willow.web;
import com.willow.entity.Department;
import com.willow.entity.Employee;
import com.willow.mapper.DepartmentMapper;
import com.willow.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmpController {
@Autowired
private EmployeeMapper employeeMapper;
@Autowired
private DepartmentMapper departmentMapper;
// 访问 :http://localhost:8080/emp/getId/1
@RequestMapping("/emp/getId/{id}")
public Employee getEmpById(@PathVariable Integer id ){
return employeeMapper.getEmpById(id);
}
// 访问http://localhost:8080/emp/[email protected]&dId=1
@RequestMapping("/emp/addEmp")
public void addEmp(Employee employee){
employeeMapper.insertEmp(employee);
}
//http://localhost:8080/dept/getByid/1
@RequestMapping("/dept/getByid/{id}")
public Department getDetpById(@PathVariable Integer id){
return departmentMapper.getDeptById(id);
}
//http://localhost:8080/dept/addDept?departmentName=1
@RequestMapping("/dept/addDept")
public void addDept(Department department){
departmentMapper.insertDept(department);
}
}
启动类访问:
http://localhost:8080/dept/addDept?departmentName=1
mybatis驼峰命名扩展部分:
mapper注解方式:
package com.willow.config;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true); //驼峰命名转换配置
}
};
}
}
xml配置方式驼峰命名法:
创建xml文件mybatis-config.xml
代码地址:https://github.com/yangliuwilow/springboot-mybatis