十四、SpringBoot之資料訪問整合MyBatis
阿新 • • 發佈:2018-12-15
- pom.xml
<!--引入mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!-- 引入druid資料來源--> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency>
- application.yml(配置資料來源相關屬性)
spring: datasource: #資料來源基本配置 username: root password: 123456 url: jdbc:mysql://172.16.40.146:3306/mybatis 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 maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 #註解版 mybatis: config-location: classpath:mybatis/mybatis-config.xml 指定全域性配置檔案的位置 mapper-locations: classpath:mybatis/mapper/*.xml 指定sql對映檔案的位置
- DruidConfig(配置資料來源相關屬性)
@Configuration public class DruidConfig { //繫結配置檔案裡的spring.datasource.xxx @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; } }
- JavaBean(建立JavaBean)
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 dId;
- Controller
@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;
@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
@GetMapping("/dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}
@GetMapping("/emp/{id}")
public Employee getEmp(@PathVariable("id") Integer id){
return employeeMapper.getEmpById(id);
}
}
- Mapper
//1.註解版
//指定這是一個操作資料庫的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);
}
2.配置版
//@Mapper或者@MapperScan將介面掃描裝配到容器中
//@Mapper
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
public void insertEmp(Employee employee);
}
//使用MapperScan批量掃描所有的Mapper介面;
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisApplication.class, args);
}
}
<!--配置版-->
<?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.atguigu.springboot.mapper.EmployeeMapper">
<select id="getEmpById" resultType="com.atguigu.springboot.bean.Employee">
SELECT * FROM employee WHERE id=#{id}
</select>
<insert id="insertEmp">
INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>
MybatisConfig
//註解版
//自定義MyBatis的配置規則;給容器中新增一個ConfigurationCustomizer;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
//配置駝峰命名法
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
配置版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>