1.POM文件配置
<?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.willow</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>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> <!--引入druid--> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.8</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- mybatis 启动类--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
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<String,String> 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<String,String> initParams = new HashMap<>(); initParams.put("exclusions","*.js,*.css,/druid/*"); //排除的请求 bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); //拦截的请求 return bean; } }
4.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.willow.mapper.EmployeeMapper"> <select id="getEmpById" resultType="com.willow.entity.Employee"> SELECT * FROM employee WHERE id=#{id} </select> <insert id="insertEmp" parameterType="com.willow.entity.Employee"> INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId}) </insert> </mapper>
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/addEmp?lastName=yl1&gender=2&[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
<?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>代码地址:https://github.com/yangliuwilow/springboot-mybatis