srpingboot整合mybatis 注解版
前期准备
开发环境
- 开发工具:IDEA
- JDK:1.8
- 技术:SpringBoot、Maven、Mybatis
创建项目
Maven依赖
用的druid的数据源 添加上坐标
<?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>cn.vp</groupId> <artifactId>springbootmybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springbootmybatis</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.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> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
SpringBoot配置文件
这里使用yml格式的配置文件,新增application.yml。
spring: datasource: druid: # 数据源基本配置 username: root password: 123 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test 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,slf4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
SpringBoot会自动加载application.yml相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中。
实体类
package cn.vp.entity; public class Department { private Integer id; private String departmentName; public Department() { } public Department(int i, String string) { this.id = i; this.departmentName = string; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } @Override public String toString() { return "Department [id=" + id + ", departmentName=" + departmentName + "]"; } }
dao类
package cn.vp.dao; import cn.vp.entity.Department; import org.apache.ibatis.annotations.*; @Mapper public interface DepartmentDao { @Insert("INSERT INTO `Department` (`departmentName`) VALUES (#{departmentName})") public int addDepartment(Department department); @Delete("DELETE FROM department where id=#{id}") public int deleteById(Integer id); @Update("UPDATE `Department` SET `departmentName`=#{departmentName} WHERE (`id`=#{id})") public int updateDepartment(Department department); @Select("SELECT * from department where id=#{id}") public Department queryById(@Param("id") Integer id); }
数据源配置类
package cn.vp.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 DataSourcesConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.druid") public DataSource getDataSources() { return new DruidDataSource(); } /** * 配置druid后台管理的servlet * * @return */ @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean bean = 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");//禁止访问的ip bean.setInitParameters(initParams); return bean; } /** * 配置druid后台管理的filter * * @return */ @Bean public FilterRegistrationBean druidFilter() { FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String, String> initParams = new HashMap<>(); //设置不拦截的路径 *.cs *.js /druid/* initParams.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParams); //设置filter拦截 那些请求 bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }
测试类
package cn.vp.dao; import cn.vp.entity.Department; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DepartmentDaoTest { @Autowired private DepartmentDao departmentDao; @Test public void addDepartment() { } @Test public void deleteById() { } @Test public void updateDepartment() { Department department=new Department(); department.setId(1); department.setDepartmentName("武汉办事处"); int i = departmentDao.updateDepartment(department); System.out.println("受影响的行数:"+i); } @Test public void queryById() { } }