建表语句
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lastName` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`gender` int(2) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
项目目录
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springboot</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-mybatis</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<!--<version>1.5.10.RELEASE</version>-->
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml配置
spring:
datasource:
username: root
password: root
url: jdbc:mysql://192.168.25.131:3306/mybatis?autoReconnect=true
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
# mybatis配置路径文件
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
# schema:
# - classpath:sql/department.sql
# - classpath:sql/employee.sql
数据库配置 DataSourceConfig
package com.springboot.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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 DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource")
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
return dataSource;
}
//配置Druid的监控
//配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","admin");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
registrationBean.setInitParameters(initParams);
return registrationBean;
}
//配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
MybatisConfig
package com.springboot.config;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisConfig {
/**
* 自定义mybatis配置规则
* @return
*/
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
//设置驼峰
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
实体类
public class Department {
private Integer id;
private String departmentName;
//get/set省略...
}
package com.springboot.bean;
public class Employee {
private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer dId;
// get/set省略...
}
Mapper
package com.springboot.mapper;
import com.springboot.bean.Department;
import org.apache.ibatis.annotations.*;
/**
* mybatis注解
*/
//@Mapper
public interface DepartmentMapper{
@Options(useGeneratedKeys = true, keyProperty = "id") //主键回填
@Insert("insert into department(departmentName) values (#{departmentName})")
int insert(Department department);
@Select("select * from department where id = #{id}")
Department selectById(Integer id);
@Delete("delete from department where id = #{id}")
int deleteById(Integer id);
@Update("update department set departmentName = #{departmentName} where id = #{id}")
int update(Department department);
}
package com.springboot.mapper;
import com.springboot.bean.Employee;
import org.apache.ibatis.annotations.Options;
/**
* mybatis XML配置文件
*/
//@Mapper
public interface EmployeeMapper {
int insert(Employee employee);
Employee selectById(Integer id);
}
mapper XML文件配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.springboot.mapper.EmployeeMapper">
<insert id="insert" parameterType="com.springboot.bean.Employee" useGeneratedKeys="true" keyProperty="id">
insert into employee(lastName, email, gender, d_id) values(#{lastName}, #{email}, #{gender}, #{dId})
</insert>
<select id="selectById" resultType="com.springboot.bean.Employee">
select * from employee where id = #{id}
</select>
</mapper>
mybatis XML文件配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
Controller
package com.springboot.controller;
import com.springboot.bean.Employee;
import com.springboot.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* Created by liujiatai on 2018/9/1.
*/
@RestController
@RequestMapping("employee")
public class EmployeeController {
@Autowired
EmployeeMapper employeeMapper;
@PostMapping("save")
public Employee insert(@RequestBody Employee employee) {
employeeMapper.insert(employee);
return employee;
}
@GetMapping("select/{id}")
public Employee selectById(@PathVariable("id") Integer id){
return employeeMapper.selectById(id);
}
}
package com.springboot.controller;
import com.springboot.mapper.DepartmentMapper;
import com.springboot.bean.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* Created by liujiatai on 2018/9/1.
*/
@RestController
@RequestMapping("dept")
public class DepartmentController {
@Autowired
DepartmentMapper departmentMapper;
@PostMapping("save")
public Department insert(@RequestBody Department department) {
departmentMapper.insert(department);
return department;
}
@GetMapping("select/{id}")
public Department selectById(@PathVariable("id") Integer id) {
return departmentMapper.selectById(id);
}
@PutMapping("save")
public int update(@RequestBody Department department) {
return departmentMapper.update(department);
}
@GetMapping("delete/{id}")
public int deleteById(@PathVariable("id") Integer id) {
return departmentMapper.deleteById(id);
}
}