1、创建Spring Initializr工程,勾选web,mysql,mybatis,jdbc
2、导入druid依赖
3、在application.yml中导入druid配置,可以复制粘贴
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://10.15.76.103:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.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: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
mapper-locations: classpath:/mybatis/mapper/*.xml
4、编写DruidConfig配置类,复制粘贴,datasource是sql下的
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
@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","10.15.75.147");
bean.setInitParameters(initParams);
return bean;
}
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
HashMap<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*,js,*.css,/druid/*");
bean.setInitParameters(initParams);;
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
5、在数据库中手动建表。
6、创建pojo包下创建实体类
7、mapper包下创建对应mapper(如果没有在接口上写@Mapper的话,就要在主程序上写MapperScan("路径"))
@Mapper public interface DepartmentMapper { @Select("select * from department where id =#{id}") Department getDeptById(Integer id); @Options(useGeneratedKeys = true,keyProperty = "id") @Insert("insert into department(departmentName) values(#{departmentName})") int insertDept(Department department); @Delete("delete from department where id =#{id}") int deleteDeptById(Integer id); @Update("update department set departmentName=#{departmentName} where id =#{id}") int updateDept(Department department); }
8、在controller包下编写deptController类
@RestController public class DeptController { @Autowired DepartmentMapper departmentMapper; @GetMapping("/dept/{id}") Department getDeptById(@PathVariable("id") Integer id){ return departmentMapper.getDeptById(id); } @GetMapping("/dept") public Department insertDept(Department department){ departmentMapper.insertDept(department); return department; }
}