第一步、用idea初始化器创建springboot项目勾选web模块sql模块勾选jdbc、mybatis、和mysql(视情况定需要什么勾选什么),然后创建项目。
创建完之后检查pom文件:
里面会有对应的依赖:
mysql的依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
mybatis依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency>
jdbc依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
由于我们要用druid所以要导入相关依赖:
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.8</version> </dependency>
二、写配置文件:我使用的application.properties当然也可以用yml写
#jdbc连接时候localhost不要加—!!!!! spring.datasource.url=jdbc:mysql://localhost:3306/mybatis spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver #spring.datasource.type= spring.datasource.initialization-mode=always #如果建完表记得注释掉这句话和删除对应路径下的文件 #spring.datasource.schema=classpath:sql/department.sql #多个扫描直接用,分割 #spring.datasource.schema=classpath:sql/employee.sql,classpath:sql/department.sql spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #连接池的配置信息 spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 spring.datasource.maxWait=60000 spring.datasource.timeBetweenEvictionRunsMillis=60000 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 spring.datasource.filters=stat,wall,log4j spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #mybatis配置 mybatis.mapper-locations=classpath:mybatis/mapper/*.xml mybatis.config-location=classpath:mybatis/mybatis-config.xml
第三步、把配置信息注入进去使其生效,当我们写完这些druid的配置之后并不会生效因为,springboot默认的没有,所以我们要写配置类 Druidconfig:
package com.tom.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; } }
第三步、如果测试lo4j的错就把对应的依赖导入:
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
启动成功会进入druid后台先让你登录。
接下来整合mybatis:
第一步:先建表,直接把建表sql放到resource下运行项目即可。我是在resource下面建个sql文件夹,application.protperties中一定要把路径写对:
#多个扫描直接用,分割 spring.datasource.schema=classpath:sql/employee.sql,classpath:sql/department.sql
建完表之后记得注释掉,不然每次启动项目都会重新建
第二步,写bean类,跟传统的写实体类一样。
第三步、写mybatis的配置类:
package com.tom.config; import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @MapperScan(value = "com.tom.mapper") @Configuration public class MybatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer(){ return new ConfigurationCustomizer() { @Override public void customize(org.apache.ibatis.session.Configuration configuration) { //配置驼峰命名映射 configuration.setMapUnderscoreToCamelCase(true); } }; } }
注意:@MapperScan(value = "com.tom.mapper")用于批量扫描mapper也可以写在主类里。
第四步、写接口
package com.tom.mapper; import com.tom.bean.Department; import org.apache.ibatis.annotations.*; //@Mapper public interface DepartmentMapper { @Select("select * from department where id=#{id}") public Department getDepartmentById(Integer id); @Delete("delete from department where id=#{id}") public int deleteDepartmentById(Integer id); // 是否使用自增主键,以及哪个是主键属性 @Options(useGeneratedKeys = true,keyProperty = "id") @Insert("insert into department(departmentName) values (#{departmentName})") public int insertDept(Department department); @Update("updata department set departmentName=#{departmentName}where id=#{id}") public int updateDept(Department department); }
第五步、写controller
package com.tom.controller; ; import com.tom.bean.Department; import com.tom.bean.Employee; import com.tom.mapper.DepartmentMapper; import com.tom.mapper.EmployeeMapper; 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; import javax.annotation.Resource; @RestController public class DeptController { @Autowired DepartmentMapper departmentMapper; @Resource EmployeeMapper employeeMapper; @GetMapping("/dept/{id}") public Department getDepartment(@PathVariable("id") Integer id){ return departmentMapper.getDepartmentById(id); } @GetMapping("/dept") public Department insertDept(Department department){ departmentMapper.insertDept(department); return department; } @GetMapping("/emp/{id}") public Employee getEmployee(@PathVariable("id") Integer id) { return employeeMapper.getEmployeeById(id); } }
上面主要介绍的是配置类整合mybatis当然还有xml文件整合方法:
第一、写接口:
package com.tom.mapper; import com.tom.bean.Employee; public interface EmployeeMapper { public Employee getEmployeeById(Integer id); public void insertEmp(Employee employee); }
第二、写全局mybatis-config.xml配置路径为:
内容(相当于mybatisconfig配置类):
<?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>
第三步、写接口映射和对应的sql语句:
<?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.tom.mapper.EmployeeMapper"> <select id="getEmployeeById" resultType="com.tom.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>
注意:namespace 和id分别写上接口类路径和方法名。
第四步、在application.properties中配置:
#mybatis配置 mybatis.mapper-locations=classpath:mybatis/mapper/*.xml mybatis.config-location=classpath:mybatis/mybatis-config.xml