MP实战系列(一)之入门框架搭建和使用
mybatis plus官网:https://github.com/baomidou/mybatis-plus
上面有对应的实际例子,直接导入即可用。
mybatis plus官方的怎么介绍,我就不在这里多说了,大家进入上方网址即可。
不过在此说明,mybatis plus绝对非常好用,比mybatis generator还好用,虽然mybatis逆向工程单表增删改查自动生成,不过我觉得它生成的动态sql和一些QueryVo之类的太不友好了。而mybatis plus只需继承,Dao继承BaseMapper<T>,Service继承IService<T>,Service实现类继承ServiceImpl<DAO,T>并实现Service,然后在src/main/resource下只需保留一个mybatis放置的xml文件即可,里面什么resultMap都不需要写,一片空白即可,除非特殊的需求,需要多个实体管理,一多对,多对多等。对于有mybatis的基础学习mybatis plus是非常简单的。不过初学者导入官网项目试着运行跑起来后,切不可抱着运行没问题或者是效果出的来就不管了,官方文档还是要看的。虽然说这个文档没有面面俱到,不过让你心中有个数或有个大概,这样对于以后学习还是非常有帮助的。
pom的依赖和spring+springmvc+mybatis其实也差不多,这里的mybaits plus依赖其实里面也封装了mybatis
下面的spring和mybatis的xml配置文件,除了mybatis plus加入一部分有点区别于之前的ssm配置,不过大致还是一样的。复制过来,修改即用。
运行环境:maven+jdk8+eclipse+window10(ubun16.04没问题)+tomcat8
项目中使用mybatis plus早就想写总结了,我希望将我遇见的问题或者是使用的感受与大家一起分享
所以才决定写一个这系列的文章,一来总结,二来分享
下面演示示例加上个人见解
pom文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lms.demo</groupId> <artifactId>LMS</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <properties> <!-- 文件拷贝时的编码 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- 编译时的编码 --> <maven.compiler.encoding>UTF-8</maven.compiler.encoding> <spring.version>4.3.13.RELEASE</spring.version> <junit.version>4.12</junit.version> <druid.version>1.1.0</druid.version> <fastjson.version>1.2.8</fastjson.version> <mybaitsplus.version>2.1.8</mybaitsplus.version> <mysql.version>5.1.38</mysql.version> <log4j.version>1.2.17</log4j.version> <slf4j.version>1.7.19</slf4j.version> <aspectjweaver.version>1.8.8</aspectjweaver.version> <fileupload.version>1.3.1</fileupload.version> <jstl.version>1.2</jstl.version> <commons-io.version>2.5</commons-io.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> <ruedigermoeller-fst.version>2.56</ruedigermoeller-fst.version> <json.version>20170516</json.version> <dozer.version>5.5.1</dozer.version> <poi.version>3.14</poi.version> </properties> <dependencies> <!-- JUnit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <!-- jsp --> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>compile</scope> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>compile</scope> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <!-- AOP --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectjweaver.version}</version> </dependency> <!-- FileUpload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${fileupload.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!-- Mybatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>${mybaitsplus.version}</version> </dependency> <!-- Mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- Druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- FastJson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!-- Log --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>de.ruedigermoeller</groupId> <artifactId>fst</artifactId> <version>${ruedigermoeller-fst.version}</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.3</version> </dependency> <!-- Json in java --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20170516</version> </dependency> <!-- Email --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> <!-- 条形码、二维码生成 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.0</version> </dependency> <!-- User Agent --> <dependency> <groupId>eu.bitwalker</groupId> <artifactId>UserAgentUtils</artifactId> <version>1.20</version> </dependency> <!-- Apache HTTP --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <!-- Jsoup HTTP --> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.9.1</version> </dependency> <!-- 图片Meta获取 --> <dependency> <groupId>com.drewnoakes</groupId> <artifactId>metadata-extractor</artifactId> <version>2.9.1</version> </dependency> <!-- 缩略图工具 --> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency> <!-- 图片验证码生成 --> <dependency> <groupId>com.bladejava</groupId> <artifactId>blade-patchca</artifactId> <version>1.0.5</version> </dependency> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.9.5</version> </dependency> <!-- Java xml --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!-- XPath xml --> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> <version>1.1.6</version> </dependency> <!-- Snake YAML --> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.17</version> </dependency> <!-- Bean To Bean copy --> <dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>${dozer.version}</version> </dependency> <!-- POI Office Tools --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${poi.version}</version> <exclusions> <exclusion> <artifactId>commons-codec</artifactId> <groupId>commons-codec</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>${poi.version}</version> </dependency> <!-- pinyin4j --> <dependency> <groupId>com.belerweb</groupId> <artifactId>pinyin4j</artifactId> <version>2.5.0</version> </dependency> <!-- Apache Tools Ant Tar Zip --> <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.9.7</version> </dependency> <!-- File MimeType ContentType --> <dependency> <groupId>net.sf.jmimemagic</groupId> <artifactId>jmimemagic</artifactId> <version>0.1.3</version> <exclusions> <exclusion> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> </exclusion> <exclusion> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-xc</artifactId> </exclusion> <exclusion> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-jaxrs</artifactId> </exclusion> <exclusion> <artifactId>log4j</artifactId> <groupId>log4j</groupId> </exclusion> </exclusions> </dependency> <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.9.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.squareup.okio/okio --> <dependency> <groupId>com.squareup.okio</groupId> <artifactId>okio</artifactId> <version>1.13.0</version> </dependency> <!-- swagger --> <dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> <version>1.0.2</version> </dependency> </dependencies> <build> <plugins> <!-- 指定编译版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!-- YUI Compressor (CSS/JS压缩) --> <!-- <plugin> <groupId>net.alchim31.maven</groupId> <artifactId>yuicompressor-maven-plugin</artifactId> <version>1.5.1</version> <executions> <execution> <phase>prepare-package</phase> <goals> <goal>compress</goal> </goals> </execution> </executions> <configuration> <encoding>UTF-8</encoding> <jswarn>false</jswarn> <nosuffix>true</nosuffix> <linebreakpos>30000</linebreakpos> <force>true</force> <includes> <include>**/*.js</include> <include>**/*.css</include> </includes> <excludes> <exclude>**/*.min.js</exclude> <exclude>**/*.min.css</exclude> </excludes> <aggregations> <aggregation> <removeIncluded>true</removeIncluded> <insertNewLine>true</insertNewLine> <inputDir>${project.build.directory}/${project.build.finalName}</inputDir> <output>${project.build.directory}/${project.build.finalName}/app/js/app.pack.js</output> <includes> <include>app/js/app*.js</include> </includes> <excludes> <exclude>**/**min.js</exclude> </excludes> </aggregation> </aggregations> </configuration> </plugin> --> </plugins> <finalName>${project.artifactId}</finalName> </build> <repositories> <repository> <id>aliyun-repos</id> <name>Aliyun Repository</name> <url>http://maven.aliyun.com/nexus/content/groups/public</url> <releases><enabled>true</enabled></releases> <snapshots><enabled>false</enabled></snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>aliyun-repos</id> <name>Aliyun Repository</name> <url>http://maven.aliyun.com/nexus/content/groups/public</url> <releases><enabled>true</enabled></releases> <snapshots><enabled>false</enabled></snapshots> </pluginRepository> </pluginRepositories> </project>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- | plugins在配置文件中的位置必须符合要求,否则会报错,顺序如下: | properties?, settings?, | typeAliases?, typeHandlers?, | objectFactory?,objectWrapperFactory?, | plugins?, | environments?, databaseIdProvider?, mappers? |--> <configuration> <!-- | 全局配置设置 | | 可配置选项 默认值, 描述 | | aggressiveLazyLoading true, 当设置为‘true’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。 | multipleResultSetsEnabled true, 允许和不允许单条语句返回多个数据集(取决于驱动需求) | useColumnLabel true, 使用列标签代替列名称。不同的驱动器有不同的作法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。 | useGeneratedKeys false, 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 | autoMappingBehavior PARTIAL, 指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。 | defaultExecutorType SIMPLE, 配置和设定执行器,SIMPLE 执行器执行其它语句。REUSE 执行器可能重复使用prepared statements 语句,BATCH执行器可以重复执行语句和批量更新。 | defaultStatementTimeout null, 设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时 | --> <settings> <!-- 这个配置使全局的映射器启用或禁用缓存 --> <setting name="cacheEnabled" value="true"/> <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="defaultExecutorType" value="REUSE"/> <setting name="defaultStatementTimeout" value="25000"/> </settings> </configuration>
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- Controller包(自动注入) --> <context:component-scan base-package="com.lms.controller"/> <mvc:default-servlet-handler/> <!-- FastJson注入 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!-- 避免IE执行AJAX时,返回JSON出现下载文件 --> <!-- FastJson --> <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 --> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <!-- <property name="features"> <array value-type="com.alibaba.fastjson.serializer.SerializerFeature"> 避免循环引用 <value>DisableCircularReferenceDetect</value> 是否输出值为null的字段 <value>WriteMapNullValue</value> 数值字段如果为null,输出为0,而非null <value>WriteNullNumberAsZero</value> 字符类型字段如果为null,输出为"",而非null <value>WriteNullStringAsEmpty</value> List字段如果为null,输出为[],而非null <value>WriteNullListAsEmpty</value> Boolean字段如果为null,输出为false,而非null <value>WriteNullBooleanAsFalse</value> </array> </property> --> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 上传限制 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上传文件大小限制为31M,31*1024*1024 --> <property name="maxUploadSize" value="32505856"/> </bean> </beans>
spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}"/> <property name="username" value="${jdbc_username}"/> <property name="password" value="${jdbc_password}"/> <!-- 初始化连接大小 --> <property name="initialSize" value="0"/> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20"/> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20"/> <!-- 连接池最小空闲 --> <property name="minIdle" value="0"/> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000"/> <property name="validationQuery" value="${validationQuery}"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000"/> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true"/> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800"/> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true"/> <!-- 监控数据库 --> <property name="filters" value="mergeStat"/> </bean> <!-- 慢SQL记录 --> <bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter"> <!-- 慢sql时间设置,即执行时间大于500毫秒的都是慢sql --> <property name="slowSqlMillis" value="500"/> <property name="logSlowSql" value="true"/> </bean> <bean id="log-filter" class="com.alibaba.druid.filter.logging.Log4jFilter"> <property name="dataSourceLogEnabled" value="true" /> <property name="statementExecutableSqlLogEnable" value="true" /> </bean> <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"> </bean> <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype"> <property name="patterns"> <list> <value>com.lms.service.*</value> <value>com.lms.controller.*</value> </list> </property> </bean> <aop:config> <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" /> </aop:config> <!-- Spring整合Mybatis,更多查看文档:http://mp.baomidou.com --> <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描Mapping.xml文件 --> <property name="mapperLocations" value="classpath:mybatis/system/*.xml"/> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <property name="typeAliasesPackage" value="com.lms.entity"/> <property name="typeEnumsPackage" value="com.lms.enums"/> <property name="plugins"> <array> <!-- 分页插件配置 --> <bean id="paginationInterceptor" class="com.baomidou.mybatisplus.plugins.PaginationInterceptor"> </bean> </array> </property> <!-- 全局配置注入 --> <property name="globalConfig" ref="globalConfig" /> </bean> <bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration"> <!-- AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID") --> <property name="idType" value="2" /> <!-- MYSQL->`mysql` ORACLE->`oracle` DB2->`db2` H2->`h2` HSQL->`hsql` SQLITE->`sqlite` POSTGRE->`postgresql` SQLSERVER2005->`sqlserver2005` SQLSERVER->`sqlserver` --> <!-- Oracle需要添加该项 --> <!-- <property name="dbType" value="oracle" /> --> <!-- 全局表为下划线命名设置 true --> <!-- <property name="dbColumnUnderline" value="true" /> --> <property name="metaObjectHandler"> <bean class="com.lms.common.MyMetaObjectHandler" /> </property> </bean> <!-- MyBatis 动态扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.lms.dao"/> </bean> <!-- 配置事务管理 --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 事务管理 属性 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="append*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="modify*" propagation="REQUIRED"/> <tx:method name="edit*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="remove*" propagation="REQUIRED"/> <tx:method name="repair" propagation="REQUIRED"/> <tx:method name="get*" propagation="REQUIRED" read-only="true"/> <tx:method name="find*" propagation="REQUIRED" read-only="true"/> <tx:method name="load*" propagation="REQUIRED" read-only="true"/> <tx:method name="search*" propagation="REQUIRED" read-only="true"/> <tx:method name="datagrid*" propagation="REQUIRED" read-only="true"/> <tx:method name="*" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice> <!-- 配置切面 --> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.lms.service..*.*(..))"/> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice"/> </aop:config> </beans>
spring.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config.properties"/> <!-- Service包(自动注入) --> <context:component-scan base-package="com.lms.service"/> <import resource="classpath:spring/spring-mybatis.xml"/> </beans>
config.properties
validationQuery=SELECT 1 jdbc_url=jdbc:mysql://127.0.0.1:3306/lms?useUnicode=true&characterEncoding=UTF-8 jdbc_username=root jdbc_password=1234
log4j.properties(本地调式环境使用DeBug,DeBug打印日志更为详细,生产环境建议日志级别使用Info)
log4j.rootLogger=DEBUG,CONSOLE,A
log4j.addivity.org.apache=false
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} -%-4r [%t] %-5p %x - %m%n
log4j.appender.CONSOLE.Target=System.out
#log4j.appender.CONSOLE.charset=utf-8
log4j.appender.CONSOLE.encoding=utf-8
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.A=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A.File=${catalina.home}/logs/yo_log/PurePro_
log4j.appender.A.DatePattern=yyyy-MM-dd'.log'
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=[FH_sys] %d{yyyy-MM-dd HH\:mm\:ss} %5p %c{1}\:%L \: %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
实体类:
package com.lms.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
/**
* lms系统用户基本信息表
*
* @author youcong
* @date 2018-04-20 19:30:29
*/
@TableName("user")
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Integer id;
/**
* 用户id
*/
@TableField("user_id")
private String userId;
/**
* 系统分配昵称
*/
@TableField("nick_name")
private String nickName;
/**
* 真实姓名
*/
@TableField("real_name")
private String realName;
/**
* 手机号
*/
private String mobile;
/**
* 邮箱
*/
private String email;
/**
*
*/
@TableField("sms_signature")
private String smsSignature;
/**
* 头像
*/
private String icon;
/**
* 性别
*/
private Integer gender;
/**
* 证件号
*/
@TableField("idcard_no")
private String idcardNo;
/**
* 设置:
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取:
*/
public Integer getId() {
return id;
}
/**
* 设置:用户id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* 获取:用户id
*/
public String getUserId() {
return userId;
}
/**
* 设置:系统分配昵称
*/
public void setNickName(String nickName) {
this.nickName = nickName;
}
/**
* 获取:系统分配昵称
*/
public String getNickName() {
return nickName;
}
/**
* 设置:真实姓名
*/
public void setRealName(String realName) {
this.realName = realName;
}
/**
* 获取:真实姓名
*/
public String getRealName() {
return realName;
}
/**
* 设置:手机号
*/
public void setMobile(String mobile) {
this.mobile = mobile;
}
/**
* 获取:手机号
*/
public String getMobile() {
return mobile;
}
/**
* 设置:邮箱
*/
public void setEmail(String email) {
this.email = email;
}
/**
* 获取:邮箱
*/
public String getEmail() {
return email;
}
/**
* 设置:
*/
public void setSmsSignature(String smsSignature) {
this.smsSignature = smsSignature;
}
/**
* 获取:
*/
public String getSmsSignature() {
return smsSignature;
}
/**
* 设置:头像
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
* 获取:头像
*/
public String getIcon() {
return icon;
}
/**
* 设置:性别
*/
public void setGender(Integer gender) {
this.gender = gender;
}
/**
* 获取:性别
*/
public Integer getGender() {
return gender;
}
/**
* 设置:证件号
*/
public void setIdcardNo(String idcardNo) {
this.idcardNo = idcardNo;
}
/**
* 获取:证件号
*/
public String getIdcardNo() {
return idcardNo;
}
}
解说:(1)@TableName是mybatis plus对表的注解,每个实体必须要加,不然会导致表不存在异常。
(2)@TableId对主键的注解 @TableId中有一个属性叫type是枚举类型,该属性主要作用是主键以什么形式存在,例如IdType.AUTO自增或UUID。
(3)@TableField像及了mybatis中的resultMap,在mybatis中为什么要使用resultMap,因为当实体中的属性名与数据库中的表不一致时需要手动映射,resultMap的作用在于手动映射,既然说了resultMap就不能不说resultType,resultType当实体属性与表字段一致时自动映射。 在mybatis plus使用@TableField的场景与mybatis中使用resultMap的是一致的。@TableField中还有一个属性不能不提,就是exist,这个属性属于boolean类型,默认为true,意思是是否在数据表中存在,true存在,false不存在,这个的应用场景是当某个实体中需要包含其他实体时,可使用该属性,否则自动生成的查会报错,使用自动生成的查有关方法,默认是查所有数据表所有字段,当然可使用setSqlSelect()方法指定需要查的字段,可以在一定程度上避免该错误的出现,不然导致的错误最有可能就是找不到该字段异常(column not exist),使用exist属性可直接避免,当然也可以在该属性中加入static或transient修饰,与exist的作用本质上是一样的。
DAO:
package com.lms.dao; import java.util.Map; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.lms.entity.UserEntity; /** * lms系统用户基本信息表 * * @author youcong * @date 2018-04-20 22:22:29 */ public interface UserDao extends BaseMapper<UserEntity> { }
解说:BaseMapper<T>中包含的就是一系列增删改查,maven项目中可Ctrl+鼠标点击进去查看源码,源码所有注释都有,非常浅显易懂,如果你需要加入自定义sql直接写就行,跟mybatis一样,在该类中新增方法,只需在对应的xml中配置即可
Service:
package com.lms.service; import java.util.Map; import com.baomidou.mybatisplus.service.IService; import com.lms.entity.UserEntity; /** * lms系统用户基本信息表 * * @author youcong * @date 2018-04-20 22:22:29 */ public interface UserService extends IService<UserEntity> { }
解说:IService<T>同DAO也是一样的,查看源码一目了然
Service实现类:
package com.lms.service.impl; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.lms.dao.UserDao; import com.lms.entity.UserEntity; import com.lms.service.UserService; /**] * * @author youcong * */ @Service("userService") public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService { }
解说:@Service注解的作用也是同mybatis之前那样也是一样,这个注解的作用扫描Service层,自动注解spring容器
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>LMS</display-name> <!-- 加载配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring.xml</param-value> </context-param> <!-- 字符过滤器 拦截所有 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- druid连接池拦截器 --> <filter> <filter-name>DruidWebStatFilter</filter-name> <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class> <init-param> <param-name>exclusions</param-name> <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value> </init-param> </filter> <filter-mapping> <filter-name>DruidWebStatFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 上下文监听 --> <listener> <description>Spring监听器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 缓存清除监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 静态资源放行 --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/view/</url-pattern> <url-pattern>/css/</url-pattern> <url-pattern>/js/*"</url-pattern> <url-pattern>/images/*</url-pattern> <url-pattern>/fonticon/*</url-pattern> <url-pattern>/layui/*</url-pattern> <url-pattern>*.html</url-pattern> <url-pattern>*.js</url-pattern> <url-pattern>*.css</url-pattern> <url-pattern>*.jpg</url-pattern> <url-pattern>*.png</url-pattern> <url-pattern>/lib/*</url-pattern> <url-pattern>/font/*</url-pattern> <url-pattern>/lang/*</url-pattern> </servlet-mapping> <!-- 前端控制器 拦截 --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description>SpringMVC</description> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- druid相关信息 --> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> <init-param> <!-- 用户名 --> <param-name>loginUsername</param-name> <param-value>druid</param-value> </init-param> <init-param> <!-- 密码 --> <param-name>loginPassword</param-name> <param-value>druid</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <!-- session过期时间 --> <session-config> <session-timeout>30</session-timeout> </session-config> <!-- 欢迎页 --> <welcome-file-list> <welcome-file>test.html</welcome-file> </welcome-file-list> </web-app>
MyMetaObjectHandler
package com.lms.common; import java.util.Date; import org.apache.ibatis.reflection.MetaObject; import com.baomidou.mybatisplus.mapper.MetaObjectHandler; /** * 自定义填充处理器 */ public class MyMetaObjectHandler extends MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("ctime", new Date(), metaObject); } @Override public boolean openUpdateFill() { return false; } @Override public void updateFill(MetaObject metaObject) { // 关闭更新填充、这里不执行 } }
UserDao.xml
<?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.lms.dao.UserDao"> </mapper>
解说:这个xml里面什么也没有,一具空壳,但是没有这空壳也是万万不行的,这就好像mybatis除了xm方式,还有注解的方式,尽管注解的方式现在很少用,用过mybatis注解的人都知道一点,随着业务的开展,sql会越来越多,写在dao中的sql也越来越多,这就不解耦了,而且mybatis使用注解的前提,必须还是要有一个空壳xml的。之所以jdbc没人用了,最大的缺点就是java代码与sql紧密度高,也就是耦合度高,所以mybatis注解几乎现在没人用,很大程度也是这个原因。使用xml方便管理。而mybatis plus也能用xml,当然同时也是可以用mybatis注解的方式,mybatis plus开发团队也同时一再声明过,mybatis plus在mybatis的基础上只做增强不做改变。所以mybatis的各方面特性也是可以用的,丝毫不影响对于mybatis习惯的开发者们。
Junit单元测试:
package test; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.lms.entity.UserEntity; import com.lms.dao.UserDao; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring/spring.xml") public class JunitTest { @Autowired private UserDao ud; @Test public void testName2() throws Exception { List<UserEntity> list =ud.selectList(null); for (UserEntity u : list) { System.out.println(u); } } }
解说:单元测试和之前的spring+mybatis也是一样的,没有任何变化
mybatis plus如果要问我最喜欢它的地方是什么?
答:可以从这么几个方面说。
第一,封装的增删改查(多条件查询,分页查询等等应有尽有),使我开发效率得到很大的提升,虽然说增删改查可以cv大法解决,但是也是不小的工作量,使用mybaits plus开发效率得到非常大的提升,使我更能专注于业务逻辑;
第二,xml是无比的简洁,而mybatis逆向工程看起来不太友好(这里声明不针对mybatis);
第三,注解是如此的亲易近人,如何的让人痛快,之前使用时,还挺疑惑,自动生成的我如何sql优化呢,开发者们都知道一点,一个系统的瓶颈与sql方面有很大的紧密度的,没想到mybatis plus只需一个方法,sql优化也做到了;
之前也时常造访github和码云,发现里面也有不少用mybatis plus,其中比较有名的就是人人开源,该代码生成器完全可以挪用过来,之前一个库四五十张表,一个敲太累了,逆向工程的话,也不太符合需求,直接果断的用人人开源的代码生成器(该代码生成器原理也是基于mybatis plus),不过它生成只需改一部分即可用了。运行完全没问题。不过,这个小部分问题,我还要再研究研究这个人人开源的代码生成器。使其更能符合我的需求。
人人开源的代码生成器帮助我提升了不少效率,与mybatis plus完全无缝结合,本人在此推荐。
该官网为:http://www.renren.io/