SpringBoot+Mybatis
最近一直在面试
遇到一个机试要求整合SpringBoot+MyBatis的公司,就顺便整理一下吧。(采用Mybatis配置文件版,比较熟悉这种开发)
开发工具 IDEA
一.建立基本框架
勾选Lombok便于实体类get,set方法
1.改application.properties为yml文件,在yml文件中加入druid配置信息
spring: datasource: # 数据源基本配置 username: root password: root driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis1?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC 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
2.修改pom
引入阿里连接池druid和log4j依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.8</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
3.添加druid的配置类
package com.zhh.springbootmybatis.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.autoconfigure.SpringBootApplication; 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; /** * @Author zhh * @Date 2019/7/19 12:28 * @Version 1.0 **/ @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.1.102");//拒绝访问的ip地址,这里我写了本机ip 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; } }
4.启动一下
二、数据库mybatis1
1.建表,这里弄了两个表employee,department
数据库语句
DROP TABLE IF EXISTS `department`; CREATE TABLE `department` ( `id` int(11) NOT NULL AUTO_INCREMENT, `departmentName` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of department -- ---------------------------- -- ---------------------------- -- Table structure for employee -- ---------------------------- DROP TABLE IF EXISTS `employee`; CREATE TABLE `employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, `lastName` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `gender` int(2) DEFAULT NULL, `d_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.mybatis全局配置文件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>
3.mybatis逆向生成
3.1pom中设置插件
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <!--声明配置文件xml的位置--> <configuration> <configurationFile>src/main/resources/mybatis/generatorConfig.xml</configurationFile> </configuration> </plugin>
3.2 mybatis逆向生成配置文件内容
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <!--利用MyBatis Generator里面的Xml文件格式,复制成为resource的xml文件,并进行修改--> <generatorConfiguration> <!--找到MySQL驱动包的路径--> <classPathEntry location="G:\dataSource\dataSourceDriver\mysql-connector-java-5.1.47.jar" /> <!--配置连接MySQL数据库的信息--> <context id="inputdb" targetRuntime="MyBatis3"> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis1" userId="root" password="root"> </jdbcConnection> <!--会将数据库里的int类型数据转换为Java里的bigDecimals --> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!--配置各个文件的相对路径和项目路径--> <!--产生实体类,需要和App是同级的--> <javaModelGenerator targetPackage="com.zhh.springbootmybatis2.entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--映射文件,一定是在resources中的--> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources/mybatis"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!--底层dao--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.zhh.springbootmybatis2.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!--将example类型设为false,否则实体类里面会多一个example的类exampleStudent --> <!--表明为数据库的表明,生成实体类Student,会自动生成到entity的目录中--> <table tableName="employee" domainObjectName="Employee" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> <table tableName="department" domainObjectName="Department" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> </context> </generatorConfiguration>
3.3 执行
一般就能成功,不成功根据异常百度解决