springboot整合mybatis

    xiaoxiao2022-07-02  113

    一.首先新建工程

    二.一定要引入mybatis-spring-boot-starter

    <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency>

    依赖关系: 引入数据源

    <!--引入druid数据源--> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.8</version> </dependenc>

    引入log4j的依赖:

    <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>

    配置文件application.yml:

    spring: datasource: # 数据源基本配置 username: root password: 123 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis 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

    配置类:

    package com.example.springbooy06datamybatis.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 DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druid(){ return new DruidDataSource(); } //配置Druid的监控 //1、配置一个管理后台的Servlet @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); Map<String,String> initParams = new HashMap<>(); initParams.put("loginUsername","admin"); initParams.put("loginPassword","123456"); initParams.put("allow","");//默认就是允许所有访问 initParams.put("deny","192.168.15.21"); bean.setInitParameters(initParams); return bean; } //2、配置一个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; } }

    启动访问:

    3.给数据库建表

    将sql文件放在resource下的sql文件夹下: 在配置文件中加入schema:

    schema: - classpath:sql/department.sql - classpath:sql/employee.sql

    4.加入实体类

    省略get set ,构造方法

    public class Department { private Integer id; private String departmentName; } public class Employee { private Integer id; private String lastName; private Integer gender; private String email; private Integer d_id; }

    5.注解映射

    编写mapper文件:

    package com.example.springbooy06datamybatis.mapper; import com.example.springbooy06datamybatis.bean.Department; import org.apache.ibatis.annotations.*; /** * @author shkstart * @date 2019/5/22- 11:49 */ //指定这是一个操作数据库的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(departmentName) values (#{departmentName})") public int insertDept(Department department); @Update("update department set departmentName = #{departmentName} where id = #{id}") public int updateDept(Department department); }

    controller层:

    package com.example.springbooy06datamybatis.controller; import com.example.springbooy06datamybatis.bean.Department; import com.example.springbooy06datamybatis.mapper.DepartmentMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** * @author shkstart * @date 2019/5/22- 11:56 */ @RestController public class DeptController { @Autowired DepartmentMapper departMentMapper; @GetMapping("/dept/{id}") public Department getDeptById(@PathVariable("id") Integer id){ return departMentMapper.getDeptById(id); } @GetMapping("/dept") public Department insertDept(Department department){ departMentMapper.insertDept(department); return department; } }

    测试:http://localhost:8080/dept/1 要实现驼峰命名规则: 需要自定义mybatis配置类: 给容器中添加一个ConfigurationCustomizer

    package com.example.springbooy06datamybatis.config; import org.apache.ibatis.session.Configuration; import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer; import org.springframework.context.annotation.Bean; /** * MyBatis的配置类,自定义驼峰命名规则 */ @org.springframework.context.annotation.Configuration public class MyBatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer(){ return new ConfigurationCustomizer() { @Override public void customize(Configuration configuration) { configuration.setMapUnderscoreToCamelCase(true); } }; } }

    若是mapper文件很多,可以在Springbooy06DataMybatisApplication中加入注解:

    @MapperScan(value = "com.example.springbooy06datamybatis.mapper")
    最新回复(0)