SSM框架 spring4.0.2+mybatis3.2.6 maven工程
废话不多说
首先引入依赖(版本我用的都是最新的):
代码块中有左边这个span标签,我不知道怎么弄了去,你们引用的时候直接替换掉就行了。
<!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.5.0</version> </dependency> <!-- 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0</version> </dependency>第一个是通用mapper的依赖,最新jar包下载前往:
http://repo1.maven.org/maven2/tk/mybatis/mapper/ 这个地址下载最新版本
(有人可能会问为什么不用这个<dependency>
<groupId>com.github.abel533</groupId>
<artifactId>mapper</artifactId>
<version>2.3.4</version>
</dependency> ,我最后再说一下网上90%的Demo都是这个但是我不用的原因)
第二个是分页插件,最新jar包前往这个地址:
http://repo1.maven.org/maven2/com/github/abel533/mapper/
同时这个插件需要JPA注解,引入即可,jar包下载前往:
http://repo1.maven.org/maven2/javax/persistence/persistence-api/
然后是配置文件:不多说上代码:
spring-mybatis.xml 代码:
这两个插件顺序其实我颠倒了是没有影响查询的,但是根据spring的加载顺序或者mybatis的加载顺序什么的(我还只是个小白没深入了解过源码和原理),网上那些大神写的通用mapper和page和pagehelper是不能颠倒顺序的(这个我最开始学确实是不能颠倒的)
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="true"> <!-- 自动扫描 --> <context:component-scan base-package="com.cn.hunst" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cn.hunst.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <property name="properties"> <value> <!-- 通用mapper --> mappers=tk.mybatis.mapper.common.Mapper </value> </property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/cn/hunst/mapping/*.xml"></property> <property name="typeAliasesPackage" value="com.cn.hunst.pojo"></property> <property name="plugins"> <array> <!-- 分页插件 --> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> <!--使用默认配置即可 --> </value> </property> </bean> <!-- 分页插件 这个是不对的--> <!-- <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> helperDialect=mysql reasonable=true supportMethodsArguments=true params=count=countSql autoRuntimeDialect=true </value> </property> </bean> --> <!-- 通用mapper 这个通用mapper运行的时候报错 --> <!-- <bean class="com.github.abel533.mapperhelper.MapperInterceptor"></bean> --> </array> </property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> </beans>
Mapper类必须继承Mapper<T> 泛型为实体类
import tk.mybatis.mapper.common.Mapper;// 此为包名
public interface UserMapper extends Mapper<User>{}
以上是所有的配置
然后说下测试:
service层:
public List<User> getLists(User user) { PageHelper.startPage(2, 10); return userMapper.select(user); }
查询结果:
继承了Mapper之后就有了这些方法,基本满足了单表查询
//根据实体类不为null的字段进行查询,条件全部使用=号and条件 List<T> select(T record); //根据实体类不为null的字段查询总数,条件全部使用=号and条件 int selectCount(T record); //根据主键进行查询,必须保证结果唯一 //单个字段做主键时,可以直接写主键的值 //联合主键时,key可以是实体类,也可以是Map T selectByPrimaryKey(Object key); //插入一条数据 //支持Oracle序列,UUID,类似Mysql的INDENTITY自动增长(自动回写) //优先使用传入的参数值,参数值空时,才会使用序列、UUID,自动增长 int insert(T record); //插入一条数据,只插入不为null的字段,不会影响有默认值的字段 //支持Oracle序列,UUID,类似Mysql的INDENTITY自动增长(自动回写) //优先使用传入的参数值,参数值空时,才会使用序列、UUID,自动增长 int insertSelective(T record); //根据实体类中字段不为null的条件进行删除,条件全部使用=号and条件 int delete(T key); //通过主键进行删除,这里最多只会删除一条数据 //单个字段做主键时,可以直接写主键的值 //联合主键时,key可以是实体类,也可以是Map int deleteByPrimaryKey(Object key); //根据主键进行更新,这里最多只会更新一条数据 //参数为实体类 int updateByPrimaryKey(T record); //根据主键进行更新 //只会更新不是null的数据 int updateByPrimaryKeySelective(T record);
说一下POJO的配置(其实都是CP):
基于JPA注解
实体类按照如下规则和数据库表进行转换,注解全部是JPA中的注解:
-
表名默认使用类名,驼峰转下划线,如
UserInfo
默认对应的表名为user_info
. -
表名可以使用
@Table(name = "tableName")
进行指定,对不符合第一条默认规则的可以通过这种方式指定表名. -
字段默认和
@Column
一样,都会作为表字段,表字段默认为Java对象的Field
名字驼峰转下划线形式. -
可以使用
@Column(name = "fieldName")
指定不符合第3条规则的字段名 -
使用
@Transient
注解可以忽略字段,添加该注解的字段不会作为表字段使用. -
建议一定是有一个
@Id
注解作为主键的字段,可以有多个@Id
注解的字段作为联合主键. -
默认情况下,实体类中如果不存在包含
@Id
注解的字段,所有的字段都会作为主键字段进行使用(这种效率极低). -
实体类可以继承使用,可以参考测试代码中的
com.github.abel533.model.UserLogin2
类. -
由于基本类型,如int作为实体类字段时会有默认值0,而且无法消除,所以实体类中建议不要使用基本类型.
除了上面提到的这些,Mapper还提供了序列(支持Oracle)、UUID(任意数据库,字段长度32)、主键自增(类似Mysql,Hsqldb)三种方式,其中序列和UUID可以配置多个,主键自增只能配置一个。
这三种方式不能同时使用,同时存在时按照 序列>UUID>主键自增
的优先级进行选择.下面是具体配置方法:
-
使用序列可以添加如下的注解:
//可以用于数字类型,字符串类型(需数据库支持自动转型)的字段 @SequenceGenerator(name="Any",sequenceName="seq_userid") @Id private Integer id;
-
使用UUID时:
//可以用于任意字符串类型长度超过32位的字段 @GeneratedValue(generator = "UUID") private String countryname;
-
使用主键自增:
//不限于@Id注解的字段,但是一个实体类中只能存在一个(继承关系中也只能存在一个) @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id;
说下为什么写这个文章:
从网上搜的那些基本上一直都在报错,有的大神提供的根本就没有这个通用mapper包,而且在spring集成分页插件中,提供的属性也是一错再错,“方言”的key都是错误的!让我折腾了一整天看源码,最后只能换了一个分页插件的包,并且属性也是默认的,我的方言默认选择的就是mysql。
而且最离谱的是,spring的sqlSessionFactory 这个Bean中plugins 属性是拦截器数组,很多大神提供的分页插件点进去根本就不是拦截器!我后来才发现。
(网上有不 在spring中集成,单独写在mybatis-config.xml 中的配置,然后在sqlSessionFactoryBean中用configLocation引用的没试过,懒得去试了,毕竟现在没有人不用spring了)
总之配置这个小小的通用mapper实在是挺闹心的,其实我技术还是非常差劲的,如果我能看动源码就迎刃而解了。
特此纪念一下!
也欢迎同门提问互相勉励
---------------------------------------二〇一八年一月三十一日 增加--------------------------------------------------
后期测试的时候发现我查询的结果集有问题:发现有些字段根本获取不到数值,实体类字段严格按照驼峰方式,但是就是获取不到数值;后来发现是实体类数据类型的问题:
问题代码:
后来发现是数据类型只能使用包装类,使用基本数据类型会报错
更正后: