0.目录结构
1.新建一个springboot项目 2.选择Web、JDBC、MyBatis、Mysql模块 3.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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mybatis</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!--添加druid依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <!--log4j--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</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>2.1.3</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> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>4.配置yml文件
spring: datasource: username: root password: shan007 url: jdbc:mysql://localhost:3306/mybatis driver-class-name: com.mysql.cj.jdbc.Driver initialization-mode: always # 在maven中添加druid依赖 type: com.alibaba.druid.pool.DruidDataSource schema: - classpath:sql/department.sql - classpath:sql/employee.sql 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'用于防火墙 # log4j改成logback 或者在maven中添加log4j依赖 filters: stat,wall,log4j # filters: stat,wall,logback maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5005.配置Druid连接池
package com.example.mybatis.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.omg.CORBA.PUBLIC_MEMBER; 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 DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druid(){ return new DruidDataSource(); } // 配置Druid的监控 // 1.配置一个管理后台的servlet @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); Map<String,String> map = new HashMap<>(); map.put("loginUsername", "shan"); //Druid后台的账号和密码 map.put("loginPassword", "1"); map.put("allow", "localhost"); map.put("deny", "10.16.13.69"); bean.setInitParameters(map); return bean; } // 2.配置一个管理后台的filter @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(new WebStatFilter()); Map<String,String> map = new HashMap<>(); map.put("exclusions", "*.js,*.css,/druid/*"); bean.setUrlPatterns(Arrays.asList("/*")); bean.setInitParameters(map); return bean; } }到这里我们可以测试一下Druid监控是否可以正常运行,运行服务器,打开浏览器输入localhost:8080/druid 可以看到Druid后台 Druid已经配置好,接下来开始写跟MVC相关的内容。 6.编写Department类
package com.example.mybatis.bean; public class Department { private Integer id; private String departmentName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String depatmentName) { this.departmentName = depatmentName; } }7.编写DepartmentMapper,mapper层是直接跟数据库打交道的,他是一个接口,只有方法名字,具体的sql语句实现在mapper.xml文件里。在Springboot中也可以通过注解,直接将sql语句写在注解中。
package com.example.mybatis.mapper; import com.example.mybatis.bean.Department; import org.apache.ibatis.annotations.*; 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(departmentName) values(#{departmentName}) ") public int insertDept(Department department); @Update("update department set departmentName=#{departmentName} where id = #{id}") public int updateDept(Department department); }6.编写DeptController
package com.example.mybatis.controller; import com.example.mybatis.bean.Department; import com.example.mybatis.mapper.DepartmentMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class DeptController { @Autowired DepartmentMapper departmentMapper; @GetMapping("/dept/{id}") public Department getDepartment(@PathVariable("id") Integer id){ return departmentMapper.getDeptById(id); } @GetMapping("/dept") public Department insert(Department department){ departmentMapper.insertDept(department); return department; } }7.开启服务器,注意,由于在yml中配置了schema,所以每次服务器重启时都会执行department.sql和employee.sql,所以此时的数据库为空。 现在我们来插入几条数据,在浏览器中输入 此时刷新数据库, 我们发现一个问题,即id为null,我们在Mapper的inserDept中设置主键即可
@Options(useGeneratedKeys = true, keyProperty = "id") @Insert("insert into department(departmentName) values (#{departmentName})") public int insertDept(Department department);重启服务器,继续刚刚的步骤。要注意,department表中的数据会清空。所以我们重新插入数据。 可以看到,已经显示了id。我们再试试查询,http://localhost:8080/dept/1表示查询id为1的部门信息。 再进入druid后台,http://localhost:8080/druid,在这里我们可以监控到sql语句。 8.配置自己的Mybatis规则 我们将数据库的列名改一下,改成department_name 相应的,修改mapper中的sql语句
重启服务器,直接在数据库中插入数据。 但是我们却查询不出来departmentName
原因是javabean中的属性名叫departmentName,而数据库字段名为department_name。 如果有配置文件,我们可以在配置文件中开启驼峰命名法,现在没有配置文件,我们可以 来配置自己的Mybatis规则,编写MybatisConfig类,开启驼峰命名法
package com.example.mybatis.config; import org.apache.ibatis.session.Configuration; import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer; import org.springframework.context.annotation.Bean; // 自定义mybatis配置规则:给容器中添加一个ConfigurationCustomizer @org.springframework.context.annotation.Configuration public class MybatisConfig { @Bean //加入容器 // 自定义配置都要实现ConfigurationCustomizer接口 public ConfigurationCustomizer configurationCustomizer(){ return new ConfigurationCustomizer() { @Override public void customize(Configuration configuration) { configuration.setMapUnderscoreToCamelCase(true); // 开启驼峰命名法启动规则 } }; } }此时启动服务器,就可以正常查询数据了。 最后一点,Mapper非常多,每个Mapper类中都要添加注释@Map 此时我们可以直接在主配置中添加@MapperScan,全局扫描Mapper,或者在MybatisConfig中添加@MapperScan
package com.example.mybatis; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan(value = "com.example.mybatis.mapper") @SpringBootApplication public class MybatisApplication { public static void main(String[] args) { SpringApplication.run(MybatisApplication.class, args); } }