From e9fe41bbfebdc5a044e35ceaaef93c4998387994 Mon Sep 17 00:00:00 2001 From: abel533 Date: Thu, 11 Dec 2014 23:49:11 +0800 Subject: [PATCH 01/10] =?UTF-8?q?=E6=94=B9=E4=B8=BAspring3.x=E7=89=88?= =?UTF-8?q?=E6=9C=AC.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- .../mybatis/mapperhelper/MapperHelper.java | 2 ++ .../com/isea533/mybatis/service/BaseService.java | 16 ---------------- .../com/isea533/mybatis/service/DemoService.java | 6 +++++- src/main/resources/applicationContext.xml | 9 +-------- 5 files changed, 9 insertions(+), 26 deletions(-) delete mode 100644 src/main/java/com/isea533/mybatis/service/BaseService.java diff --git a/pom.xml b/pom.xml index 1ddf7df..e67f861 100644 --- a/pom.xml +++ b/pom.xml @@ -173,7 +173,7 @@ org.springframework spring-framework-bom - 4.1.2.RELEASE + 3.2.12.RELEASE pom import diff --git a/src/main/java/com/isea533/mybatis/mapperhelper/MapperHelper.java b/src/main/java/com/isea533/mybatis/mapperhelper/MapperHelper.java index 29364cb..dc5da0d 100644 --- a/src/main/java/com/isea533/mybatis/mapperhelper/MapperHelper.java +++ b/src/main/java/com/isea533/mybatis/mapperhelper/MapperHelper.java @@ -135,6 +135,8 @@ private void initSpringVersion() { int MajorVersion = Integer.parseInt(springVersion.substring(0, springVersion.indexOf("."))); if (MajorVersion > 3) { spring4 = true; + } else { + spring4 = false; } } } catch (Exception e) { diff --git a/src/main/java/com/isea533/mybatis/service/BaseService.java b/src/main/java/com/isea533/mybatis/service/BaseService.java deleted file mode 100644 index fdf6393..0000000 --- a/src/main/java/com/isea533/mybatis/service/BaseService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.isea533.mybatis.service; - -import com.isea533.mybatis.mapperhelper.Mapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -/** - * Created by liuzh on 2014/12/11. - */ -@Service -public class BaseService { - - @Autowired - protected Mapper mapper; - -} diff --git a/src/main/java/com/isea533/mybatis/service/DemoService.java b/src/main/java/com/isea533/mybatis/service/DemoService.java index 76785b0..63a952d 100644 --- a/src/main/java/com/isea533/mybatis/service/DemoService.java +++ b/src/main/java/com/isea533/mybatis/service/DemoService.java @@ -1,5 +1,6 @@ package com.isea533.mybatis.service; +import com.isea533.mybatis.mapper.Country2Mapper; import com.isea533.mybatis.mapper.CountryMapper; import com.isea533.mybatis.model.Country; import com.isea533.mybatis.model.Country2; @@ -16,10 +17,13 @@ * @author liuzh */ @Service -public class DemoService extends BaseService { +public class DemoService { @Autowired private CountryMapper countryMapper; + @Autowired + private Country2Mapper mapper; + private JdbcTemplate jdbcTemplate; @Autowired diff --git a/src/main/resources/applicationContext.xml b/src/main/resources/applicationContext.xml index 20d4d69..4bde1ba 100644 --- a/src/main/resources/applicationContext.xml +++ b/src/main/resources/applicationContext.xml @@ -34,13 +34,6 @@ - @@ -54,7 +47,7 @@ - + From bab116a2b3e1d0e80348f747a887745b5e2e26dd Mon Sep 17 00:00:00 2001 From: abel533 Date: Sat, 7 Mar 2015 17:49:40 +0800 Subject: [PATCH 02/10] =?UTF-8?q?spring3=E7=89=88=E6=9C=AC=E5=8D=87?= =?UTF-8?q?=E7=BA=A7=E5=88=B0=E6=9C=80=E6=96=B0=E7=89=88=E9=80=9A=E7=94=A8?= =?UTF-8?q?Mapper=E5=92=8C=E5=88=86=E9=A1=B5=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 20 + .../mybatis/mapper/Country2Mapper.java | 2 +- .../isea533/mybatis/mapper/CountryMapper.java | 2 +- .../mybatis/mapper/UserInfoMapper.java | 2 +- .../mybatis/mapper/UserLoginMapper.java | 2 +- .../mybatis/mapperhelper/EntityHelper.java | 419 ------------ .../isea533/mybatis/mapperhelper/Mapper.java | 70 -- .../mybatis/mapperhelper/MapperHelper.java | 607 ------------------ .../mapperhelper/MapperInterceptor.java | 79 --- .../mybatis/mapperhelper/MapperProvider.java | 342 ---------- .../mybatis/mapperhelper/MapperSpring.java | 45 -- .../mybatis/mapperhelper/MapperTemplate.java | 436 ------------- .../com/isea533/mybatis/pagehelper/Page.java | 178 ----- .../mybatis/pagehelper/PageHelper.java | 215 ------- .../isea533/mybatis/pagehelper/PageInfo.java | 272 -------- .../isea533/mybatis/pagehelper/SqlParser.java | 242 ------- .../isea533/mybatis/pagehelper/SqlUtil.java | 549 ---------------- .../isea533/mybatis/service/DemoService.java | 2 +- src/main/resources/applicationContext.xml | 15 +- .../com/isea533/mybatis/test/BasicTest.java | 13 + .../mybatis/test/NoAutoWiredMapperTest.java | 25 + .../mybatis/test/PageEntityMapperTest.java | 30 + 22 files changed, 104 insertions(+), 3463 deletions(-) delete mode 100644 src/main/java/com/isea533/mybatis/mapperhelper/EntityHelper.java delete mode 100644 src/main/java/com/isea533/mybatis/mapperhelper/Mapper.java delete mode 100644 src/main/java/com/isea533/mybatis/mapperhelper/MapperHelper.java delete mode 100644 src/main/java/com/isea533/mybatis/mapperhelper/MapperInterceptor.java delete mode 100644 src/main/java/com/isea533/mybatis/mapperhelper/MapperProvider.java delete mode 100644 src/main/java/com/isea533/mybatis/mapperhelper/MapperSpring.java delete mode 100644 src/main/java/com/isea533/mybatis/mapperhelper/MapperTemplate.java delete mode 100644 src/main/java/com/isea533/mybatis/pagehelper/Page.java delete mode 100644 src/main/java/com/isea533/mybatis/pagehelper/PageHelper.java delete mode 100644 src/main/java/com/isea533/mybatis/pagehelper/PageInfo.java delete mode 100644 src/main/java/com/isea533/mybatis/pagehelper/SqlParser.java delete mode 100644 src/main/java/com/isea533/mybatis/pagehelper/SqlUtil.java create mode 100644 src/test/java/com/isea533/mybatis/test/BasicTest.java create mode 100644 src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java create mode 100644 src/test/java/com/isea533/mybatis/test/PageEntityMapperTest.java diff --git a/pom.xml b/pom.xml index e67f861..e84eadc 100644 --- a/pom.xml +++ b/pom.xml @@ -12,6 +12,9 @@ UTF-8 ${basedir}/src/main/java + + 2.0.1 + 3.6.1 @@ -99,6 +102,10 @@ org.springframework spring-aop + + org.springframework + spring-test + @@ -167,6 +174,19 @@ persistence-api 1.0 + + + + com.github.pagehelper + pagehelper + ${pagehelper.version} + + + + com.github.abel533 + mapper + ${mapper.version} + diff --git a/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java b/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java index 284bd76..e27b417 100644 --- a/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java +++ b/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java @@ -1,6 +1,6 @@ package com.isea533.mybatis.mapper; -import com.isea533.mybatis.mapperhelper.Mapper; +import com.github.abel533.mapper.Mapper; import com.isea533.mybatis.model.Country2; import com.isea533.mybatis.model.Country2Example; import org.apache.ibatis.annotations.Param; diff --git a/src/main/java/com/isea533/mybatis/mapper/CountryMapper.java b/src/main/java/com/isea533/mybatis/mapper/CountryMapper.java index a93f0ad..7f1260e 100644 --- a/src/main/java/com/isea533/mybatis/mapper/CountryMapper.java +++ b/src/main/java/com/isea533/mybatis/mapper/CountryMapper.java @@ -1,6 +1,6 @@ package com.isea533.mybatis.mapper; -import com.isea533.mybatis.mapperhelper.Mapper; +import com.github.abel533.mapper.Mapper; import com.isea533.mybatis.model.Country; public interface CountryMapper extends Mapper { diff --git a/src/main/java/com/isea533/mybatis/mapper/UserInfoMapper.java b/src/main/java/com/isea533/mybatis/mapper/UserInfoMapper.java index 5086187..da5bc0e 100644 --- a/src/main/java/com/isea533/mybatis/mapper/UserInfoMapper.java +++ b/src/main/java/com/isea533/mybatis/mapper/UserInfoMapper.java @@ -1,6 +1,6 @@ package com.isea533.mybatis.mapper; -import com.isea533.mybatis.mapperhelper.Mapper; +import com.github.abel533.mapper.Mapper; import com.isea533.mybatis.model.UserInfo; public interface UserInfoMapper extends Mapper { diff --git a/src/main/java/com/isea533/mybatis/mapper/UserLoginMapper.java b/src/main/java/com/isea533/mybatis/mapper/UserLoginMapper.java index 55bcfe7..f47623a 100644 --- a/src/main/java/com/isea533/mybatis/mapper/UserLoginMapper.java +++ b/src/main/java/com/isea533/mybatis/mapper/UserLoginMapper.java @@ -1,6 +1,6 @@ package com.isea533.mybatis.mapper; -import com.isea533.mybatis.mapperhelper.Mapper; +import com.github.abel533.mapper.Mapper; import com.isea533.mybatis.model.UserLogin; public interface UserLoginMapper extends Mapper { diff --git a/src/main/java/com/isea533/mybatis/mapperhelper/EntityHelper.java b/src/main/java/com/isea533/mybatis/mapperhelper/EntityHelper.java deleted file mode 100644 index 5d95f10..0000000 --- a/src/main/java/com/isea533/mybatis/mapperhelper/EntityHelper.java +++ /dev/null @@ -1,419 +0,0 @@ -/* - The MIT License (MIT) - - Copyright (c) 2014 abel533@gmail.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -package com.isea533.mybatis.mapperhelper; - -import javax.persistence.*; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.*; - -/** - * 实体类工具类 - *

项目地址 : https://github.com/abel533/Mapper

- * - * @author liuzh - */ -public class EntityHelper { - - /** - * 实体对应表的配置信息 - */ - public static class EntityTable { - private String name; - private String catalog; - private String schema; - - public void setTable(Table table){ - this.name = table.name(); - this.catalog = table.catalog(); - this.schema = table.schema(); - } - - public String getName() { - return name; - } - - public String getCatalog() { - return catalog; - } - - public String getSchema() { - return schema; - } - - public String getPrefix() { - if (catalog != null && catalog.length() > 0) { - return catalog; - } - if (schema != null && schema.length() > 0) { - return catalog; - } - return ""; - } - } - - /** - * 实体字段对应数据库列的信息 - */ - public static class EntityColumn { - private String property; - private String column; - private Class javaType; - private String sequenceName; - private boolean id = false; - private boolean uuid = false; - private boolean identity = false; - private String generator; - - public String getProperty() { - return property; - } - - public void setProperty(String property) { - this.property = property; - } - - public String getColumn() { - return column; - } - - public void setColumn(String column) { - this.column = column; - } - - public Class getJavaType() { - return javaType; - } - - public void setJavaType(Class javaType) { - this.javaType = javaType; - } - - public String getSequenceName() { - return sequenceName; - } - - public void setSequenceName(String sequenceName) { - this.sequenceName = sequenceName; - } - - public boolean isId() { - return id; - } - - public void setId(boolean id) { - this.id = id; - } - - public boolean isUuid() { - return uuid; - } - - public void setUuid(boolean uuid) { - this.uuid = uuid; - } - - public boolean isIdentity() { - return identity; - } - - public void setIdentity(boolean identity) { - this.identity = identity; - } - - public String getGenerator() { - return generator; - } - - public void setGenerator(String generator) { - this.generator = generator; - } - } - - /** - * 实体类 => 表对象 - */ - private static final Map, EntityTable> entityTableMap = new HashMap, EntityTable>(); - - /** - * 实体类 => 全部列属性 - */ - private static final Map, List> entityClassColumns = new HashMap, List>(); - - /** - * 实体类 => 主键信息 - */ - private static final Map, List> entityClassPKColumns = new HashMap, List>(); - - /** - * 获取表对象 - * - * @param entityClass - * @return - */ - public static EntityTable getEntityTable(Class entityClass) { - EntityTable entityTable = entityTableMap.get(entityClass); - if (entityTable == null) { - initEntityNameMap(entityClass); - entityTable = entityTableMap.get(entityClass); - } - if (entityTable == null) { - throw new RuntimeException("无法获取实体类" + entityClass.getCanonicalName() + "对应的表名!"); - } - return entityTable; - } - - /** - * 获取全部列 - * - * @param entityClass - * @return - */ - public static List getColumns(Class entityClass) { - //可以起到初始化的作用 - getEntityTable(entityClass); - return entityClassColumns.get(entityClass); - } - - /** - * 获取主键信息 - * - * @param entityClass - * @return - */ - public static List getPKColumns(Class entityClass) { - //可以起到初始化的作用 - getEntityTable(entityClass); - return entityClassPKColumns.get(entityClass); - } - - /** - * 获取查询的Select - * - * @param entityClass - * @return - */ - public static String getSelectColumns(Class entityClass) { - List columnList = getColumns(entityClass); - StringBuilder selectBuilder = new StringBuilder(); - boolean skipAlias = Map.class.isAssignableFrom(entityClass); - for (EntityColumn entityColumn : columnList) { - selectBuilder.append(entityColumn.getColumn()); - if (!skipAlias && !entityColumn.getColumn().equalsIgnoreCase(entityColumn.getProperty())) { - selectBuilder.append(" ").append(entityColumn.getProperty().toUpperCase()).append(","); - } else { - selectBuilder.append(","); - } - } - return selectBuilder.substring(0, selectBuilder.length() - 1); - } - - /** - * 获取查询的Select - * - * @param entityClass - * @return - */ - public static String getAllColumns(Class entityClass) { - List columnList = getColumns(entityClass); - StringBuilder selectBuilder = new StringBuilder(); - for (EntityColumn entityColumn : columnList) { - selectBuilder.append(entityColumn.getColumn()).append(","); - } - return selectBuilder.substring(0, selectBuilder.length() - 1); - } - - /** - * 获取主键的Where语句 - * - * @param entityClass - * @return - */ - public static String getPrimaryKeyWhere(Class entityClass) { - List entityColumns = EntityHelper.getPKColumns(entityClass); - StringBuilder whereBuilder = new StringBuilder(); - for (EntityHelper.EntityColumn column : entityColumns) { - whereBuilder.append(column.getColumn()).append(" = ?").append(" AND "); - } - return whereBuilder.substring(0, whereBuilder.length() - 4); - } - - /** - * 初始化实体属性 - * - * @param entityClass - */ - public static synchronized void initEntityNameMap(Class entityClass) { - if (entityTableMap.get(entityClass) != null) { - return; - } - //表名 - EntityTable entityTable = null; - if (entityClass.isAnnotationPresent(Table.class)) { - Table table = entityClass.getAnnotation(Table.class); - if (!table.name().equals("")) { - entityTable = new EntityTable(); - entityTable.setTable(table); - } - } - if (entityTable == null) { - entityTable = new EntityTable(); - entityTable.name = camelhumpToUnderline(entityClass.getSimpleName()).toUpperCase(); - } - entityTableMap.put(entityClass, entityTable); - //列 - List fieldList = getAllField(entityClass, null); - List columnList = new ArrayList(); - List pkColumnList = new ArrayList(); - for (Field field : fieldList) { - //排除字段 - if (field.isAnnotationPresent(Transient.class)) { - continue; - } - EntityColumn entityColumn = new EntityColumn(); - if (field.isAnnotationPresent(Id.class)) { - entityColumn.setId(true); - } - String columnName = null; - if (field.isAnnotationPresent(Column.class)) { - Column column = field.getAnnotation(Column.class); - columnName = column.name(); - } else { - columnName = camelhumpToUnderline(field.getName()); - } - entityColumn.setProperty(field.getName()); - entityColumn.setColumn(columnName.toUpperCase()); - entityColumn.setJavaType(field.getType()); - //主键策略 - Oracle序列,MySql自动增长,UUID - if (field.isAnnotationPresent(SequenceGenerator.class)) { - SequenceGenerator sequenceGenerator = field.getAnnotation(SequenceGenerator.class); - if (sequenceGenerator.sequenceName().equals("")) { - throw new RuntimeException(entityClass + "字段" + field.getName() + "的注解@SequenceGenerator未指定sequenceName!"); - } - entityColumn.setSequenceName(sequenceGenerator.sequenceName()); - } else if (field.isAnnotationPresent(GeneratedValue.class)) { - GeneratedValue generatedValue = field.getAnnotation(GeneratedValue.class); - if (generatedValue.generator().equals("UUID")) { - if (field.getType().equals(String.class)) { - entityColumn.setUuid(true); - } else { - throw new RuntimeException(field.getName() + " - 该字段@GeneratedValue配置为UUID,但该字段类型不是String"); - } - } else { - //允许通过generator来设置获取id的sql,例如mysql=CALL IDENTITY(),hsqldb=SELECT SCOPE_IDENTITY() - //允许通过拦截器参数设置公共的generator - if (generatedValue.strategy() == GenerationType.IDENTITY) { - //mysql的自动增长 - entityColumn.setIdentity(true); - if (!generatedValue.generator().equals("")) { - entityColumn.setGenerator(generatedValue.generator()); - } - } else { - throw new RuntimeException(field.getName() - + " - 该字段@GeneratedValue配置只允许两种形式,全部数据库通用的@GeneratedValue(generator=\"UUID\") 或者 " + - "类似mysql数据库的@GeneratedValue(strategy=GenerationType.IDENTITY[,generator=\"CALL IDENTITY()\"])"); - } - } - } - columnList.add(entityColumn); - if (entityColumn.isId()) { - pkColumnList.add(entityColumn); - } - } - if (pkColumnList.size() == 0) { - pkColumnList = columnList; - } - entityClassColumns.put(entityClass, columnList); - entityClassPKColumns.put(entityClass, pkColumnList); - } - - public static void main(String[] args) { - System.out.println(camelhumpToUnderline("userName")); - System.out.println(camelhumpToUnderline("userPassWord")); - System.out.println(camelhumpToUnderline("ISO9001")); - System.out.println(camelhumpToUnderline("hello_world")); - } - - /** - * 将驼峰风格替换为下划线风格 - */ - public static String camelhumpToUnderline(String str) { - final int size; - final char[] chars; - final StringBuilder sb = new StringBuilder( - (size = (chars = str.toCharArray()).length) * 3 / 2 + 1); - char c; - for (int i = 0; i < size; i++) { - c = chars[i]; - if (isUppercaseAlpha(c)) { - sb.append('_').append(c); - } else { - sb.append(toUpperAscii(c)); - } - } - return sb.charAt(0) == '_'? sb.substring(1): sb.toString(); - } - - public static boolean isUppercaseAlpha(char c) { - return (c >= 'A') && (c <= 'Z'); - } - - public static char toUpperAscii(char c) { - if (isUppercaseAlpha(c)) { - c -= (char) 0x20; - } - return c; - } - - /** - * 获取全部的Field - * - * @param entityClass - * @param fieldList - * @return - */ - private static List getAllField(Class entityClass, List fieldList) { - if (fieldList == null) { - fieldList = new ArrayList(); - } - if (entityClass.equals(Object.class)) { - return fieldList; - } - Field[] fields = entityClass.getDeclaredFields(); - for (Field field : fields) { - //排除静态字段,解决bug#2 - if (!Modifier.isStatic(field.getModifiers())) { - fieldList.add(field); - } - } - if (entityClass.getSuperclass() != null - && !entityClass.getSuperclass().equals(Object.class) - && !Map.class.isAssignableFrom(entityClass.getSuperclass()) - && !Collection.class.isAssignableFrom(entityClass.getSuperclass())) { - return getAllField(entityClass.getSuperclass(), fieldList); - } - return fieldList; - } -} \ No newline at end of file diff --git a/src/main/java/com/isea533/mybatis/mapperhelper/Mapper.java b/src/main/java/com/isea533/mybatis/mapperhelper/Mapper.java deleted file mode 100644 index 3010124..0000000 --- a/src/main/java/com/isea533/mybatis/mapperhelper/Mapper.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - The MIT License (MIT) - - Copyright (c) 2014 abel533@gmail.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -package com.isea533.mybatis.mapperhelper; - -import org.apache.ibatis.annotations.DeleteProvider; -import org.apache.ibatis.annotations.InsertProvider; -import org.apache.ibatis.annotations.SelectProvider; -import org.apache.ibatis.annotations.UpdateProvider; - -import java.util.List; - -/** - * 通用Mapper接口,其他接口继承该接口即可 - *

项目地址 : https://github.com/abel533/Mapper

- * - * @param 不能为空 - * @author liuzh - */ -public interface Mapper { - - @SelectProvider(type = MapperProvider.class, method = "dynamicSQL") - List select(T record); - - @SelectProvider(type = MapperProvider.class, method = "dynamicSQL") - int selectCount(T record); - - @SelectProvider(type = MapperProvider.class, method = "dynamicSQL") - T selectByPrimaryKey(Object key); - - @InsertProvider(type = MapperProvider.class, method = "dynamicSQL") - int insert(T record); - - @InsertProvider(type = MapperProvider.class, method = "dynamicSQL") - int insertSelective(T record); - - @DeleteProvider(type = MapperProvider.class, method = "dynamicSQL") - int delete(T key); - - @DeleteProvider(type = MapperProvider.class, method = "dynamicSQL") - int deleteByPrimaryKey(Object key); - - @UpdateProvider(type = MapperProvider.class, method = "dynamicSQL") - int updateByPrimaryKey(T record); - - @UpdateProvider(type = MapperProvider.class, method = "dynamicSQL") - int updateByPrimaryKeySelective(T record); - -} diff --git a/src/main/java/com/isea533/mybatis/mapperhelper/MapperHelper.java b/src/main/java/com/isea533/mybatis/mapperhelper/MapperHelper.java deleted file mode 100644 index dc5da0d..0000000 --- a/src/main/java/com/isea533/mybatis/mapperhelper/MapperHelper.java +++ /dev/null @@ -1,607 +0,0 @@ -/* - The MIT License (MIT) - - Copyright (c) 2014 abel533@gmail.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -package com.isea533.mybatis.mapperhelper; - -import org.apache.ibatis.annotations.DeleteProvider; -import org.apache.ibatis.annotations.InsertProvider; -import org.apache.ibatis.annotations.SelectProvider; -import org.apache.ibatis.annotations.UpdateProvider; -import org.apache.ibatis.builder.annotation.ProviderSqlSource; -import org.apache.ibatis.mapping.MappedStatement; -import org.apache.ibatis.session.Configuration; -import org.apache.ibatis.session.SqlSession; - -import java.lang.reflect.Method; -import java.util.*; - -/** - * 处理主要逻辑 - *

项目地址 : https://github.com/abel533/Mapper

- * - * @author liuzh - */ -public class MapperHelper { - - /** - * 注册的通用Mapper接口 - */ - private Map, MapperTemplate> registerMapper = new HashMap, MapperTemplate>(); - - /** - * 缓存msid和MapperTemplate - */ - private Map msIdCache = new HashMap(); - /** - * 缓存skip结果 - */ - private final Map msIdSkip = new HashMap(); - - /** - * 缓存已经处理过的Collection - */ - private Set> collectionSet = new HashSet>(); - - /** - * 是否使用的Spring - */ - private boolean spring = false; - - /** - * 是否为Spring4.x以上版本 - */ - private boolean spring4 = false; - - /** - * Spring版本号 - */ - private String springVersion; - - /** - * 默认构造方法 - */ - public MapperHelper() { - } - - /** - * 带配置的构造方法 - * - * @param properties - */ - public MapperHelper(Properties properties) { - setProperties(properties); - } - - /** - * 缓存初始化时的SqlSession - */ - private List sqlSessions = new ArrayList(); - - /** - * 针对Spring注入需要处理的SqlSession - * - * @param sqlSessions - */ - public void setSqlSessions(SqlSession[] sqlSessions) { - if (sqlSessions != null && sqlSessions.length > 0) { - this.sqlSessions.addAll(Arrays.asList(sqlSessions)); - } - } - - /** - * Spring初始化方法,使用Spring时需要配置init-method="initMapper" - */ - public void initMapper() { - //只有Spring会执行这个方法,所以Spring配置的时候,从这儿可以尝试获取Spring的版本 - //先判断Spring版本,对下面的操作有影响 - //Spring4以上支持泛型注入,因此可以扫描通用Mapper - initSpringVersion(); - for (SqlSession sqlSession : sqlSessions) { - processConfiguration(sqlSession.getConfiguration()); - } - } - - /** - * 检测Spring版本号,Spring4.x以上支持泛型注入 - */ - private void initSpringVersion() { - try { - //反射获取SpringVersion - Class springVersionClass = Class.forName("org.springframework.core.SpringVersion"); - springVersion = (String) springVersionClass.getDeclaredMethod("getVersion", null).invoke(null, null); - spring = true; - if (springVersion.indexOf(".") > 0) { - int MajorVersion = Integer.parseInt(springVersion.substring(0, springVersion.indexOf("."))); - if (MajorVersion > 3) { - spring4 = true; - } else { - spring4 = false; - } - } - } catch (Exception e) { - spring = false; - spring4 = false; - } - } - - /** - * 是否为Spring4.x以上版本 - * - * @return - */ - public boolean isSpring4() { - return spring4; - } - - /** - * 是否为Spring4.x以上版本 - * - * @return - */ - public boolean isSpring() { - return spring; - } - - /** - * 获取Spring版本号 - * - * @return - */ - public String getSpringVersion(){ - return springVersion; - } - - /** - * 通过通用Mapper接口获取对应的MapperTemplate - * - * @param mapperClass - * @return - * @throws Exception - */ - private MapperTemplate fromMapperClass(Class mapperClass) { - Method[] methods = mapperClass.getDeclaredMethods(); - Class templateClass = null; - Class tempClass = null; - Set methodSet = new HashSet(); - for (Method method : methods) { - if (method.isAnnotationPresent(SelectProvider.class)) { - SelectProvider provider = method.getAnnotation(SelectProvider.class); - tempClass = provider.type(); - methodSet.add(method.getName()); - } else if (method.isAnnotationPresent(InsertProvider.class)) { - InsertProvider provider = method.getAnnotation(InsertProvider.class); - tempClass = provider.type(); - methodSet.add(method.getName()); - } else if (method.isAnnotationPresent(DeleteProvider.class)) { - DeleteProvider provider = method.getAnnotation(DeleteProvider.class); - tempClass = provider.type(); - methodSet.add(method.getName()); - } else if (method.isAnnotationPresent(UpdateProvider.class)) { - UpdateProvider provider = method.getAnnotation(UpdateProvider.class); - tempClass = provider.type(); - methodSet.add(method.getName()); - } - if (templateClass == null) { - templateClass = tempClass; - } else if (templateClass != tempClass) { - throw new RuntimeException("一个通用Mapper中只允许存在一个MapperTemplate子类!"); - } - } - if (templateClass == null || !MapperTemplate.class.isAssignableFrom(templateClass)) { - throw new RuntimeException("接口中不存在包含type为MapperTemplate的Provider注解,这不是一个合法的通用Mapper接口类!"); - } - MapperTemplate mapperTemplate = null; - try { - mapperTemplate = (MapperTemplate) templateClass.getConstructor(Class.class, MapperHelper.class).newInstance(mapperClass, this); - } catch (Exception e) { - throw new RuntimeException("实例化MapperTemplate对象失败:" + e.getMessage()); - } - //注册方法 - for (String methodName : methodSet) { - try { - mapperTemplate.addMethodMap(methodName, templateClass.getMethod(methodName, MappedStatement.class)); - } catch (NoSuchMethodException e) { - throw new RuntimeException(templateClass.getCanonicalName() + "中缺少" + methodName + "方法!"); - } - } - return mapperTemplate; - } - - /** - * 注册通用Mapper接口 - * - * @param mapperClass - * @throws Exception - */ - public void registerMapper(Class mapperClass) { - if (registerMapper.get(mapperClass) == null) { - registerMapper.put(mapperClass, fromMapperClass(mapperClass)); - } else { - throw new RuntimeException("已经注册过的通用Mapper[" + mapperClass.getCanonicalName() + "]不能多次注册!"); - } - } - - /** - * 注册通用Mapper接口 - * - * @param mapperClass - * @throws Exception - */ - public void registerMapper(String mapperClass) { - try { - registerMapper(Class.forName(mapperClass)); - } catch (ClassNotFoundException e) { - throw new RuntimeException("注册通用Mapper[" + mapperClass + "]失败,找不到该通用Mapper!"); - } - } - - /** - * 方便Spring注入 - * - * @param mappers - */ - public void setMappers(String[] mappers) { - if (mappers != null && mappers.length > 0) { - for (String mapper : mappers) { - registerMapper(mapper); - } - } - } - - /** - * IDENTITY的可选值 - */ - public enum IdentityDialect { - DB2("VALUES IDENTITY_VAL_LOCAL()"), - MYSQL("SELECT LAST_INSERT_ID()"), - SQLSERVER("SELECT SCOPE_IDENTITY()"), - CLOUDSCAPE("VALUES IDENTITY_VAL_LOCAL()"), - DERBY("VALUES IDENTITY_VAL_LOCAL()"), - HSQLDB("CALL IDENTITY()"), - SYBASE("SELECT @@IDENTITY"), - DB2_MF("SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1"), - INFORMIX("select dbinfo('sqlca.sqlerrd1') from systables where tabid=1"); - - private String identityRetrievalStatement; - - private IdentityDialect(String identityRetrievalStatement) { - this.identityRetrievalStatement = identityRetrievalStatement; - } - - public String getIdentityRetrievalStatement() { - return identityRetrievalStatement; - } - - public static IdentityDialect getDatabaseDialect(String database) { - IdentityDialect returnValue = null; - if ("DB2".equalsIgnoreCase(database)) { - returnValue = DB2; - } else if ("MySQL".equalsIgnoreCase(database)) { - returnValue = MYSQL; - } else if ("SqlServer".equalsIgnoreCase(database)) { - returnValue = SQLSERVER; - } else if ("Cloudscape".equalsIgnoreCase(database)) { - returnValue = CLOUDSCAPE; - } else if ("Derby".equalsIgnoreCase(database)) { - returnValue = DERBY; - } else if ("HSQLDB".equalsIgnoreCase(database)) { - returnValue = HSQLDB; - } else if ("SYBASE".equalsIgnoreCase(database)) { - returnValue = SYBASE; - } else if ("DB2_MF".equalsIgnoreCase(database)) { - returnValue = DB2_MF; - } else if ("Informix".equalsIgnoreCase(database)) { - returnValue = INFORMIX; - } - return returnValue; - } - } - - //基础可配置项 - private class Config { - private String UUID; - private String IDENTITY; - private boolean BEFORE = false; - private String seqFormat; - private String catalog; - private String schema; - } - - private Config config = new Config(); - - /** - * 设置UUID - * - * @param UUID - */ - public void setUUID(String UUID) { - config.UUID = UUID; - } - - /** - * 设置主键自增回写方法,默认MYSQL - * - * @param IDENTITY - */ - public void setIDENTITY(String IDENTITY) { - IdentityDialect identityDialect = IdentityDialect.getDatabaseDialect(IDENTITY); - if (identityDialect != null) { - config.IDENTITY = identityDialect.getIdentityRetrievalStatement(); - } else { - config.IDENTITY = IDENTITY; - } - } - - /** - * 设置selectKey方法的ORDER,默认AFTER - * - * @param order - */ - public void setOrder(String order) { - config.BEFORE = "BEFORE".equalsIgnoreCase(order); - } - - /** - * 设置序列格式化,默认值"{0}.nextval" - * - * @param seqFormat - */ - public void setSeqFormat(String seqFormat) { - config.seqFormat = seqFormat; - } - - /** - * 设置catalog,默认"" - * - * @param catalog - */ - public void setCatalog(String catalog) { - config.catalog = catalog; - } - - /** - * 设置schema,默认"" - * - * @param schema - */ - public void setSchema(String schema) { - config.schema = schema; - } - - /** - * 获取表前缀,带catalog或schema - * - * @return - */ - public String getPrefix() { - if (config.catalog != null && config.catalog.length() > 0) { - return config.catalog; - } - if (config.schema != null && config.schema.length() > 0) { - return config.catalog; - } - return ""; - } - - /** - * 获取UUID生成规则 - * - * @return - */ - public String getUUID() { - if (config.UUID != null && config.UUID.length() > 0) { - return config.UUID; - } - return "@java.util.UUID@randomUUID().toString().replace(\"-\", \"\")"; - } - - /** - * 获取主键自增回写SQL - * - * @return - */ - public String getIDENTITY() { - if (config.IDENTITY != null && config.IDENTITY.length() > 0) { - return config.IDENTITY; - } - //针对mysql的默认值 - return IdentityDialect.MYSQL.getIdentityRetrievalStatement(); - } - - /** - * 获取SelectKey的Order - * - * @return - */ - public boolean getBEFORE() { - return config.BEFORE; - } - - /** - * 获取序列格式化模板 - * - * @return - */ - public String getSeqFormat() { - if (config.seqFormat != null && config.seqFormat.length() > 0) { - return config.seqFormat; - } - return "{0}.nextval"; - } - - /** - * 获取表名 - * - * @param entityClass - * @return - */ - public String getTableName(Class entityClass) { - EntityHelper.EntityTable entityTable = EntityHelper.getEntityTable(entityClass); - String prefix = entityTable.getPrefix(); - if (prefix.equals("")) { - //使用全局配置 - prefix = getPrefix(); - } - if (!prefix.equals("")) { - return prefix + "." + entityTable.getName(); - } - return entityTable.getName(); - } - - /** - * 判断当前的接口方法是否需要进行拦截 - * - * @param msId - * @return - */ - public boolean isMapperMethod(String msId) { - if (msIdSkip.get(msId) != null) { - return msIdSkip.get(msId); - } - for (Map.Entry, MapperTemplate> entry : registerMapper.entrySet()) { - if (entry.getValue().supportMethod(msId)) { - msIdSkip.put(msId, true); - return true; - } - } - msIdSkip.put(msId, false); - return false; - } - - /** - * 获取MapperTemplate - * - * @param msId - * @return - */ - private MapperTemplate getMapperTemplate(String msId) { - MapperTemplate mapperTemplate = null; - if (msIdCache.get(msId) != null) { - mapperTemplate = msIdCache.get(msId); - } else { - for (Map.Entry, MapperTemplate> entry : registerMapper.entrySet()) { - if (entry.getValue().supportMethod(msId)) { - mapperTemplate = entry.getValue(); - break; - } - } - msIdCache.put(msId, mapperTemplate); - } - return mapperTemplate; - } - - /** - * 重新设置SqlSource - * - * @param ms - */ - public void setSqlSource(MappedStatement ms) { - MapperTemplate mapperTemplate = getMapperTemplate(ms.getId()); - try { - if (mapperTemplate != null) { - mapperTemplate.setSqlSource(ms); - } - } catch (Exception e) { - throw new RuntimeException("调用方法异常:" + e.getMessage()); - } - } - - /** - * 配置属性 - * - * @param properties - */ - public void setProperties(Properties properties) { - if (properties == null) { - return; - } - String UUID = properties.getProperty("UUID"); - if (UUID != null && UUID.length() > 0) { - setUUID(UUID); - } - String IDENTITY = properties.getProperty("IDENTITY"); - if (IDENTITY != null && IDENTITY.length() > 0) { - setIDENTITY(IDENTITY); - } - String seqFormat = properties.getProperty("seqFormat"); - if (seqFormat != null && seqFormat.length() > 0) { - setSeqFormat(seqFormat); - } - String catalog = properties.getProperty("catalog"); - if (catalog != null && catalog.length() > 0) { - setCatalog(catalog); - } - String schema = properties.getProperty("schema"); - if (schema != null && schema.length() > 0) { - setSchema(schema); - } - String ORDER = properties.getProperty("ORDER"); - if (ORDER != null && ORDER.length() > 0) { - setOrder(ORDER); - } - //注册通用接口 - String mapper = properties.getProperty("mappers"); - if (mapper != null && mapper.length() > 0) { - String[] mappers = mapper.split(","); - for (String mapperClass : mappers) { - if (mapperClass.length() > 0) { - registerMapper(mapperClass); - } - } - } - } - - /** - * 处理configuration中全部的MappedStatement - * - * @param configuration - */ - public void processConfiguration(Configuration configuration) { - Collection collection = configuration.getMappedStatements(); - //防止反复处理一个 - if (collectionSet.contains(collection)) { - return; - } else { - collectionSet.add(collection); - } - int size = collection.size(); - Iterator iterator = collection.iterator(); - while (iterator.hasNext()) { - Object object = iterator.next(); - if (object instanceof MappedStatement) { - MappedStatement ms = (MappedStatement) object; - if (isMapperMethod(ms.getId())) { - if (ms.getSqlSource() instanceof ProviderSqlSource) { - setSqlSource(ms); - } - } - } - //处理过程中可能会新增selectKey,导致ms增多,所以这里判断大小,重新循环 - if (collection.size() != size) { - size = collection.size(); - iterator = collection.iterator(); - } - } - } -} \ No newline at end of file diff --git a/src/main/java/com/isea533/mybatis/mapperhelper/MapperInterceptor.java b/src/main/java/com/isea533/mybatis/mapperhelper/MapperInterceptor.java deleted file mode 100644 index 10f3618..0000000 --- a/src/main/java/com/isea533/mybatis/mapperhelper/MapperInterceptor.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - The MIT License (MIT) - - Copyright (c) 2014 abel533@gmail.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -package com.isea533.mybatis.mapperhelper; - -import org.apache.ibatis.builder.annotation.ProviderSqlSource; -import org.apache.ibatis.executor.Executor; -import org.apache.ibatis.mapping.MappedStatement; -import org.apache.ibatis.plugin.*; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; - -import java.util.Properties; - -/** - * 通用Mapper拦截器 - *

项目地址 : https://github.com/abel533/Mapper

- * - * @author liuzh - */ -@Intercepts({ - @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), - @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) -}) -public class MapperInterceptor implements Interceptor { - - private final MapperHelper mapperHelper = new MapperHelper(); - - @Override - public Object intercept(Invocation invocation) throws Throwable { - Object[] objects = invocation.getArgs(); - MappedStatement ms = (MappedStatement) objects[0]; - String msId = ms.getId(); - //不需要拦截的方法直接返回 - if (mapperHelper.isMapperMethod(msId)) { - //第一次经过处理后,就不会是ProviderSqlSource了,一开始高并发时可能会执行多次,但不影响。以后就不会在执行了 - if (ms.getSqlSource() instanceof ProviderSqlSource) { - mapperHelper.setSqlSource(ms); - } - } - Object result = invocation.proceed(); - return result; - } - - @Override - public Object plugin(Object target) { - if (target instanceof Executor) { - return Plugin.wrap(target, this); - } else { - return target; - } - } - - @Override - public void setProperties(Properties properties) { - mapperHelper.setProperties(properties); - } -} diff --git a/src/main/java/com/isea533/mybatis/mapperhelper/MapperProvider.java b/src/main/java/com/isea533/mybatis/mapperhelper/MapperProvider.java deleted file mode 100644 index b1762b4..0000000 --- a/src/main/java/com/isea533/mybatis/mapperhelper/MapperProvider.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2014 abel533@gmail.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.isea533.mybatis.mapperhelper; - -import org.apache.ibatis.builder.StaticSqlSource; -import org.apache.ibatis.mapping.MappedStatement; -import org.apache.ibatis.mapping.ParameterMapping; -import org.apache.ibatis.scripting.xmltags.*; - -import java.util.ArrayList; -import java.util.List; - -import static org.apache.ibatis.jdbc.SqlBuilder.*; - -/** - * Mappper实现类 - * - * @author liuzh - */ -public class MapperProvider extends MapperTemplate { - - public MapperProvider(Class mapperClass, MapperHelper mapperHelper) { - super(mapperClass, mapperHelper); - } - - /** - * 查询 - * - * @param ms - * @return - */ - public SqlNode select(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - //修改返回值类型为实体类型 - setResultType(ms, entityClass); - List sqlNodes = new ArrayList(); - //静态的sql部分:select column ... from table - sqlNodes.add(new StaticTextSqlNode("SELECT " - + EntityHelper.getSelectColumns(entityClass) - + " FROM " - + tableName(entityClass))); - //将if添加到 - sqlNodes.add(new WhereSqlNode(ms.getConfiguration(), getAllIfColumnNode(entityClass))); - return new MixedSqlNode(sqlNodes); - } - - /** - * 根据主键进行查询 - * - * @param ms - */ - public void selectByPrimaryKey(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - //获取主键字段映射 - List parameterMappings = getPrimaryKeyParameterMappings(ms); - //开始拼sql - BEGIN(); - //select全部列 - SELECT(EntityHelper.getSelectColumns(entityClass)); - //from表 - FROM(tableName(entityClass)); - //where条件,主键字段=#{property} - WHERE(EntityHelper.getPrimaryKeyWhere(entityClass)); - //SQL()方法获取最终SQL,使用静态SqlSource - StaticSqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), SQL(), parameterMappings); - //替换原有的SqlSource - setSqlSource(ms, sqlSource); - //将返回值修改为实体类型 - setResultType(ms, entityClass); - } - - /** - * 查询总数 - * - * @param ms - * @return - */ - public SqlNode selectCount(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - List sqlNodes = new ArrayList(); - //select count(*) from table - sqlNodes.add(new StaticTextSqlNode("SELECT COUNT(*) FROM " + tableName(entityClass))); - //获取全部列的where,if条件 - sqlNodes.add(new WhereSqlNode(ms.getConfiguration(), getAllIfColumnNode(entityClass))); - return new MixedSqlNode(sqlNodes); - } - - /** - * 插入全部 - * - * @param ms - * @return - */ - public SqlNode insert(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - List sqlNodes = new ArrayList(); - //insert into table - sqlNodes.add(new StaticTextSqlNode("INSERT INTO " + tableName(entityClass))); - //获取全部列 - List columnList = EntityHelper.getColumns(entityClass); - //Identity列只能有一个 - Boolean hasIdentityKey = false; - //处理所有的主键策略 - for (EntityHelper.EntityColumn column : columnList) { - //序列的情况,直接写入sql中,不需要额外的获取值 - if (column.getSequenceName() != null && column.getSequenceName().length() > 0) { - } else if (column.isIdentity()) { - //如果是Identity列,就需要插入selectKey - //如果已经存在Identity列,抛出异常 - if (hasIdentityKey) { - throw new RuntimeException(ms.getId() + "对应的实体类" + entityClass.getCanonicalName() + "中包含多个MySql的自动增长列,最多只能有一个!"); - } - //插入selectKey - newSelectKeyMappedStatement(ms, column); - hasIdentityKey = true; - //这种情况下,如果原先的字段有值,需要先缓存起来,否则就一定会使用自动增长 - //这是一个bind节点 - sqlNodes.add(new VarDeclSqlNode(column.getProperty() + "_cache", column.getProperty())); - } else if (column.isUuid()) { - //uuid的情况,直接插入bind节点 - sqlNodes.add(new VarDeclSqlNode(column.getProperty() + "_bind", getUUID())); - } - } - //插入全部的(列名,列名...) - sqlNodes.add(new StaticTextSqlNode("(" + EntityHelper.getAllColumns(entityClass) + ")")); - List ifNodes = new ArrayList(); - //处理所有的values(属性值,属性值...) - for (EntityHelper.EntityColumn column : columnList) { - //优先使用传入的属性值,当原属性property!=null时,用原属性 - //自增的情况下,如果默认有值,就会备份到property_cache中,所以这里需要先判断备份的值是否存在 - if (column.isIdentity()) { - ifNodes.add(getIfCacheNotNull(column,new StaticTextSqlNode("#{" + column.getProperty() + "_cache },"))); - } else { - //其他情况值仍然存在原property中 - ifNodes.add(getIfNotNull(column,new StaticTextSqlNode("#{" + column.getProperty() + "},"))); - } - //当属性为null时,如果存在主键策略,会自动获取值,如果不存在,则使用null - //序列的情况 - if (column.getSequenceName() != null && column.getSequenceName().length() > 0) { - ifNodes.add(getIfIsNull(column, new StaticTextSqlNode(getSeqNextVal(column) + " ,"))); - } else if (column.isIdentity()) { - ifNodes.add(getIfCacheIsNull(column, new StaticTextSqlNode("#{" + column.getProperty() + " },"))); - } else if (column.isUuid()) { - ifNodes.add(getIfIsNull(column, new StaticTextSqlNode("#{" + column.getProperty() + "_bind },"))); - } else { - //当null的时候,如果不指定jdbcType,oracle可能会报异常,指定VARCHAR不影响其他 - ifNodes.add(getIfIsNull(column, new StaticTextSqlNode("#{" + column.getProperty() + ",jdbcType=VARCHAR},"))); - } - } - //values(#{property},#{property}...) - sqlNodes.add(new TrimSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes), "VALUES (", null, ")", ",")); - return new MixedSqlNode(sqlNodes); - } - - /** - * 插入不为null的字段 - * - * @param ms - * @return - */ - public SqlNode insertSelective(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - List sqlNodes = new ArrayList(); - //insert into table - sqlNodes.add(new StaticTextSqlNode("INSERT INTO " + tableName(entityClass))); - //获取全部列 - List columnList = EntityHelper.getColumns(entityClass); - List ifNodes = new ArrayList(); - //Identity列只能有一个 - Boolean hasIdentityKey = false; - //当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值 - for (EntityHelper.EntityColumn column : columnList) { - //当使用序列时 - if (column.getSequenceName() != null && column.getSequenceName().length() > 0) { - //直接将列加进去 - ifNodes.add(new StaticTextSqlNode(column.getColumn() + ",")); - } else if (column.isIdentity()) { - if (hasIdentityKey) { - throw new RuntimeException(ms.getId() + "对应的实体类" + entityClass.getCanonicalName() + "中包含多个MySql的自动增长列,最多只能有一个!"); - } - //新增一个selectKey-MS - newSelectKeyMappedStatement(ms, column); - hasIdentityKey = true; - //加入该列 - ifNodes.add(new StaticTextSqlNode(column.getColumn() + ",")); - //这种情况下,如果原先的字段有值,需要先缓存起来,否则就一定会使用自动增长 - sqlNodes.add(new VarDeclSqlNode(column.getProperty() + "_cache", column.getProperty())); - } else if (column.isUuid()) { - //将UUID的值加入bind节点 - sqlNodes.add(new VarDeclSqlNode(column.getProperty() + "_bind", getUUID())); - ifNodes.add(new StaticTextSqlNode(column.getColumn() + ",")); - } else { - ifNodes.add(getIfNotNull(column,new StaticTextSqlNode(column.getColumn() + ","))); - } - } - //将动态的列加入sqlNodes - sqlNodes.add(new TrimSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes), "(", null, ")", ",")); - - ifNodes = new ArrayList(); - //处理values(#{property},#{property}...) - for (EntityHelper.EntityColumn column : columnList) { - //当参数中的属性值不为空的时候,使用传入的值 - //自增的情况下,如果默认有值,就会备份到property_cache中 - if (column.isIdentity()) { - ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + "_cache },"), column.getProperty() + "_cache != null ")); - } else { - ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + "},"), column.getProperty() + " != null ")); - } - if (column.getSequenceName() != null && column.getSequenceName().length() > 0) { - ifNodes.add(getIfIsNull(column, new StaticTextSqlNode(getSeqNextVal(column) + " ,"))); - } else if (column.isIdentity()) { - ifNodes.add(getIfCacheIsNull(column, new StaticTextSqlNode("#{" + column.getProperty() + " },"))); - } else if (column.isUuid()) { - ifNodes.add(getIfIsNull(column, new StaticTextSqlNode("#{" + column.getProperty() + "_bind },"))); - } - } - //values(#{property},#{property}...) - sqlNodes.add(new TrimSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes), "VALUES (", null, ")", ",")); - return new MixedSqlNode(sqlNodes); - } - - /** - * 通过条件删除 - * - * @param ms - * @return - */ - public SqlNode delete(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - List sqlNodes = new ArrayList(); - //delete from table - sqlNodes.add(new StaticTextSqlNode("DELETE FROM " + tableName(entityClass))); - //where/if判断条件 - sqlNodes.add(new WhereSqlNode(ms.getConfiguration(), getAllIfColumnNode(entityClass))); - return new MixedSqlNode(sqlNodes); - } - - /** - * 通过主键删除 - * - * @param ms - */ - public void deleteByPrimaryKey(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - List parameterMappings = getPrimaryKeyParameterMappings(ms); - //开始拼sql - BEGIN(); - //delete from table - DELETE_FROM(tableName(entityClass)); - //where 主键=#{property} 条件 - WHERE(EntityHelper.getPrimaryKeyWhere(entityClass)); - //静态SqlSource - StaticSqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), SQL(), parameterMappings); - //替换原有的SqlSource - setSqlSource(ms, sqlSource); - } - - /** - * 通过主键更新全部字段 - * - * @param ms - */ - public void updateByPrimaryKey(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - //映射要包含set=?和where=? - //获取set映射 - List parameterMappings = getColumnParameterMappings(ms); - //获取where主键映射 - parameterMappings.addAll(getPrimaryKeyParameterMappings(ms)); - //开始拼Sql - BEGIN(); - //update table - UPDATE(tableName(entityClass)); - //获取全部列 - List columnList = EntityHelper.getColumns(entityClass); - //拼所有的set column = ? - for (EntityHelper.EntityColumn column : columnList) { - SET(column.getColumn() + " = ?"); - } - //where 主键=#{property} 条件 - WHERE(EntityHelper.getPrimaryKeyWhere(entityClass)); - //静态SqlSource - StaticSqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), SQL(), parameterMappings); - //替换原有的SqlSource - setSqlSource(ms, sqlSource); - } - - /** - * 通过主键更新不为null的字段 - * - * @param ms - * @return - */ - public SqlNode updateByPrimaryKeySelective(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - List sqlNodes = new ArrayList(); - //update table - sqlNodes.add(new StaticTextSqlNode("UPDATE " + tableName(entityClass))); - //获取全部列 - List columnList = EntityHelper.getColumns(entityClass); - List ifNodes = new ArrayList(); - //全部的if property!=null and property!='' - for (EntityHelper.EntityColumn column : columnList) { - StaticTextSqlNode columnNode = new StaticTextSqlNode(column.getColumn() + " = #{" + column.getProperty() + "}, "); - ifNodes.add(getIfNotNull(column,columnNode)); - } - sqlNodes.add(new SetSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes))); - //获取全部的主键的列 - columnList = EntityHelper.getPKColumns(entityClass); - List whereNodes = new ArrayList(); - boolean first = true; - //where 主键=#{property} 条件 - for (EntityHelper.EntityColumn column : columnList) { - whereNodes.add(getColumnEqualsProperty(column,first)); - first = false; - } - sqlNodes.add(new WhereSqlNode(ms.getConfiguration(), new MixedSqlNode(whereNodes))); - return new MixedSqlNode(sqlNodes); - } -} diff --git a/src/main/java/com/isea533/mybatis/mapperhelper/MapperSpring.java b/src/main/java/com/isea533/mybatis/mapperhelper/MapperSpring.java deleted file mode 100644 index 24c4bc9..0000000 --- a/src/main/java/com/isea533/mybatis/mapperhelper/MapperSpring.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.isea533.mybatis.mapperhelper; - -import org.mybatis.spring.SqlSessionTemplate; -import org.mybatis.spring.mapper.MapperFactoryBean; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanPostProcessor; - -import java.util.Properties; - -/** - * 通用Mapper和Spring集成 - * - * @author liuzh - */ -public class MapperSpring implements BeanPostProcessor { - - private final MapperHelper mapperHelper = new MapperHelper(); - - /** - * 通过注入配置参数 - * - * @param properties - */ - public void setProperties(Properties properties) { - mapperHelper.setProperties(properties); - } - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - return bean; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - //对所有的SqlSessionTemplate进行处理,多数据源情况下仍然有效 - if (bean instanceof SqlSessionTemplate) { - SqlSessionTemplate sqlSessionTemplate = (SqlSessionTemplate) bean; - mapperHelper.processConfiguration(sqlSessionTemplate.getConfiguration()); - } else if (bean instanceof MapperFactoryBean) { - MapperFactoryBean mapperFactoryBean = (MapperFactoryBean) bean; - mapperHelper.processConfiguration(mapperFactoryBean.getSqlSession().getConfiguration()); - } - return bean; - } -} \ No newline at end of file diff --git a/src/main/java/com/isea533/mybatis/mapperhelper/MapperTemplate.java b/src/main/java/com/isea533/mybatis/mapperhelper/MapperTemplate.java deleted file mode 100644 index 7941d08..0000000 --- a/src/main/java/com/isea533/mybatis/mapperhelper/MapperTemplate.java +++ /dev/null @@ -1,436 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2014 abel533@gmail.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.isea533.mybatis.mapperhelper; - -import org.apache.ibatis.executor.keygen.KeyGenerator; -import org.apache.ibatis.executor.keygen.NoKeyGenerator; -import org.apache.ibatis.executor.keygen.SelectKeyGenerator; -import org.apache.ibatis.mapping.*; -import org.apache.ibatis.reflection.MetaObject; -import org.apache.ibatis.reflection.factory.DefaultObjectFactory; -import org.apache.ibatis.reflection.factory.ObjectFactory; -import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; -import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory; -import org.apache.ibatis.scripting.defaults.RawSqlSource; -import org.apache.ibatis.scripting.xmltags.*; -import org.apache.ibatis.session.Configuration; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Mapper方法 - * - * @author liuzh - */ -public abstract class MapperTemplate { - private Map methodMap = new HashMap(); - private Class mapperClass; - private MapperHelper mapperHelper; - - public MapperTemplate(Class mapperClass, MapperHelper mapperHelper) { - this.mapperClass = mapperClass; - this.mapperHelper = mapperHelper; - } - - public String dynamicSQL(Object record) { - return "dynamicSQL"; - } - - /** - * 添加映射方法 - * - * @param methodName - * @param method - */ - public void addMethodMap(String methodName, Method method) { - methodMap.put(methodName, method); - } - - public String getUUID() { - return mapperHelper.getUUID(); - } - - public String getIDENTITY() { - return mapperHelper.getIDENTITY(); - } - - public boolean getBEFORE() { - return mapperHelper.getBEFORE(); - } - - private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory(); - private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory(); - - /** - * 反射对象,增加对低版本Mybatis的支持 - * - * @param object 反射对象 - * @return - */ - public static MetaObject forObject(Object object) { - return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY); - } - - /** - * 是否支持该通用方法 - * - * @param msId - * @return - */ - public boolean supportMethod(String msId) { - Class mapperClass = getMapperClass(msId); - if (this.mapperClass.isAssignableFrom(mapperClass)) { - String methodName = getMethodName(msId); - return methodMap.get(methodName) != null; - } - return false; - } - - /** - * 设置返回值类型 - * - * @param ms - * @param entityClass - */ - protected void setResultType(MappedStatement ms, Class entityClass) { - ResultMap resultMap = ms.getResultMaps().get(0); - MetaObject metaObject = forObject(resultMap); - metaObject.setValue("type", entityClass); - } - - /** - * 重新设置SqlSource - * - * @param ms - * @param sqlSource - */ - protected void setSqlSource(MappedStatement ms, SqlSource sqlSource) { - MetaObject msObject = forObject(ms); - msObject.setValue("sqlSource", sqlSource); - } - - /** - * 重新设置SqlSource - * - * @param ms - * @throws java.lang.reflect.InvocationTargetException - * @throws IllegalAccessException - */ - public void setSqlSource(MappedStatement ms) throws Exception { - if (this.mapperClass == getMapperClass(ms.getId())) { - if (mapperHelper.isSpring4()) { - return; - } else if (mapperHelper.isSpring()) { - throw new RuntimeException("Spring4.x.x 及以上版本支持泛型注入," + - "您当前的Spring版本为" + mapperHelper.getSpringVersion() + ",不能使用泛型注入," + - "因此在配置MapperScannerConfigurer时,不要扫描通用Mapper接口类," + - "也不要在您Mybatis的xml配置文件中的中指定通用Mapper接口类."); - } else { - throw new RuntimeException("请不要在您Mybatis的xml配置文件中的中指定通用Mapper接口类."); - } - } - Method method = methodMap.get(getMethodName(ms)); - try { - if (method.getReturnType() == Void.TYPE) { - method.invoke(this, ms); - } else if (SqlNode.class.isAssignableFrom(method.getReturnType())) { - SqlNode sqlNode = (SqlNode) method.invoke(this, ms); - DynamicSqlSource dynamicSqlSource = new DynamicSqlSource(ms.getConfiguration(), sqlNode); - setSqlSource(ms, dynamicSqlSource); - } else { - throw new RuntimeException("自定义Mapper方法返回类型错误,可选的返回类型为void和SqlNode!"); - } - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (InvocationTargetException e) { - throw new RuntimeException(e.getTargetException() != null ? e.getTargetException() : e); - } - } - - /** - * 获取返回值类型 - 实体类型 - * - * @param ms - * @return - */ - public Class getSelectReturnType(MappedStatement ms) { - String msId = ms.getId(); - Class mapperClass = getMapperClass(msId); - Type[] types = mapperClass.getGenericInterfaces(); - for (Type type : types) { - if (type instanceof ParameterizedType) { - ParameterizedType t = (ParameterizedType) type; - if (t.getRawType() == this.mapperClass) { - Class returnType = (Class) t.getActualTypeArguments()[0]; - return returnType; - } - } - } - throw new RuntimeException("无法获取Mapper泛型类型:" + msId); - } - - /** - * 根据msId获取接口类 - * - * @param msId - * @return - * @throws ClassNotFoundException - */ - public static Class getMapperClass(String msId) { - String mapperClassStr = msId.substring(0, msId.lastIndexOf(".")); - try { - return Class.forName(mapperClassStr); - } catch (ClassNotFoundException e) { - throw new RuntimeException("无法获取Mapper接口信息:" + msId); - } - } - - /** - * 获取执行的方法名 - * - * @param ms - * @return - */ - public static String getMethodName(MappedStatement ms) { - return getMethodName(ms.getId()); - } - - /** - * 获取执行的方法名 - * - * @param msId - * @return - */ - public static String getMethodName(String msId) { - return msId.substring(msId.lastIndexOf(".") + 1); - } - - /** - * 根据对象生成主键映射 - * - * @param ms - * @return - */ - protected List getPrimaryKeyParameterMappings(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - List entityColumns = EntityHelper.getPKColumns(entityClass); - List parameterMappings = new ArrayList(); - for (EntityHelper.EntityColumn column : entityColumns) { - ParameterMapping.Builder builder = new ParameterMapping.Builder(ms.getConfiguration(), column.getProperty(), column.getJavaType()); - builder.mode(ParameterMode.IN); - parameterMappings.add(builder.build()); - } - return parameterMappings; - } - - /** - * 获取序列下个值的表达式 - * - * @param column - * @return - */ - protected String getSeqNextVal(EntityHelper.EntityColumn column) { - return MessageFormat.format(mapperHelper.getSeqFormat(), column.getSequenceName(), column.getColumn(), column.getProperty()); - } - - /** - * 获取实体类的表名 - * - * @param entityClass - * @return - */ - protected String tableName(Class entityClass) { - return mapperHelper.getTableName(entityClass); - } - - /** - * 返回if条件的sqlNode - *

一般类型:<if test="property!=null">columnNode</if>

- * - * @param column - * @return - */ - protected SqlNode getIfNotNull(EntityHelper.EntityColumn column, SqlNode columnNode) { - return new IfSqlNode(columnNode, column.getProperty() + " != null "); - } - - /** - * 返回if条件的sqlNode - *

一般类型:<if test="property==null">columnNode</if>

- * - * @param column - * @return - */ - protected SqlNode getIfIsNull(EntityHelper.EntityColumn column, SqlNode columnNode) { - return new IfSqlNode(columnNode, column.getProperty() + " == null "); - } - - /** - * 返回if条件的sqlNode - *

一般类型:<if test="property!=null">columnNode</if>

- * - * @param column - * @return - */ - protected SqlNode getIfCacheNotNull(EntityHelper.EntityColumn column, SqlNode columnNode) { - return new IfSqlNode(columnNode, column.getProperty() + "_cache != null "); - } - - /** - * 返回if条件的sqlNode - *

一般类型:<if test="property_cache!=null">columnNode</if>

- * - * @param column - * @return - */ - protected SqlNode getIfCacheIsNull(EntityHelper.EntityColumn column, SqlNode columnNode) { - return new IfSqlNode(columnNode, column.getProperty() + "_cache == null "); - } - - /** - * 获取 [AND] column = #{property} - * - * @param column - * @param first - * @return - */ - protected SqlNode getColumnEqualsProperty(EntityHelper.EntityColumn column, boolean first) { - return new StaticTextSqlNode((first ? "" : " AND ") + column.getColumn() + " = #{" + column.getProperty() + "} "); - } - - /** - * 获取所有列的where节点中的if判断列 - * - * @param entityClass - * @return - */ - protected SqlNode getAllIfColumnNode(Class entityClass) { - //获取全部列 - List columnList = EntityHelper.getColumns(entityClass); - List ifNodes = new ArrayList(); - boolean first = true; - //对所有列循环,生成column = #{property} - for (EntityHelper.EntityColumn column : columnList) { - ifNodes.add(getIfNotNull(column, getColumnEqualsProperty(column, first))); - first = false; - } - return new MixedSqlNode(ifNodes); - } - - /** - * 根据对象生成所有列的映射 - * - * @param ms - * @return - */ - protected List getColumnParameterMappings(MappedStatement ms) { - Class entityClass = getSelectReturnType(ms); - List entityColumns = EntityHelper.getColumns(entityClass); - List parameterMappings = new ArrayList(); - for (EntityHelper.EntityColumn column : entityColumns) { - ParameterMapping.Builder builder = new ParameterMapping.Builder(ms.getConfiguration(), column.getProperty(), column.getJavaType()); - builder.mode(ParameterMode.IN); - parameterMappings.add(builder.build()); - } - return parameterMappings; - } - - /** - * 新建SelectKey节点 - 只对mysql的自动增长有效,Oracle序列直接写到列中 - * - * @param ms - * @param column - */ - protected void newSelectKeyMappedStatement(MappedStatement ms, EntityHelper.EntityColumn column) { - String keyId = ms.getId() + SelectKeyGenerator.SELECT_KEY_SUFFIX; - if (ms.getConfiguration().hasKeyGenerator(keyId)) { - return; - } - Class entityClass = getSelectReturnType(ms); - //defaults - Configuration configuration = ms.getConfiguration(); - KeyGenerator keyGenerator = new NoKeyGenerator(); - Boolean executeBefore = getBEFORE(); - String IDENTITY = (column.getGenerator() == null || column.getGenerator().equals("")) ? getIDENTITY() : column.getGenerator(); - SqlSource sqlSource = new RawSqlSource(configuration, IDENTITY, entityClass); - - MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, keyId, sqlSource, SqlCommandType.SELECT); - statementBuilder.resource(ms.getResource()); - statementBuilder.fetchSize(null); - statementBuilder.statementType(StatementType.STATEMENT); - statementBuilder.keyGenerator(keyGenerator); - statementBuilder.keyProperty(column.getProperty()); - statementBuilder.keyColumn(null); - statementBuilder.databaseId(null); - statementBuilder.lang(configuration.getDefaultScriptingLanuageInstance()); - statementBuilder.resultOrdered(false); - statementBuilder.resulSets(null); - statementBuilder.timeout(configuration.getDefaultStatementTimeout()); - - List parameterMappings = new ArrayList(); - ParameterMap.Builder inlineParameterMapBuilder = new ParameterMap.Builder( - configuration, - statementBuilder.id() + "-Inline", - entityClass, - parameterMappings); - statementBuilder.parameterMap(inlineParameterMapBuilder.build()); - - List resultMaps = new ArrayList(); - ResultMap.Builder inlineResultMapBuilder = new ResultMap.Builder( - configuration, - statementBuilder.id() + "-Inline", - int.class, - new ArrayList(), - null); - resultMaps.add(inlineResultMapBuilder.build()); - statementBuilder.resultMaps(resultMaps); - statementBuilder.resultSetType(null); - - statementBuilder.flushCacheRequired(false); - statementBuilder.useCache(false); - statementBuilder.cache(null); - - MappedStatement statement = statementBuilder.build(); - configuration.addMappedStatement(statement); - - MappedStatement keyStatement = configuration.getMappedStatement(keyId, false); - configuration.addKeyGenerator(keyId, new SelectKeyGenerator(keyStatement, executeBefore)); - //keyGenerator - try { - MetaObject msObject = forObject(ms); - msObject.setValue("keyGenerator", configuration.getKeyGenerator(keyId)); - } catch (Exception e) { - //ignore - } - } -} \ No newline at end of file diff --git a/src/main/java/com/isea533/mybatis/pagehelper/Page.java b/src/main/java/com/isea533/mybatis/pagehelper/Page.java deleted file mode 100644 index 4175126..0000000 --- a/src/main/java/com/isea533/mybatis/pagehelper/Page.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - The MIT License (MIT) - - Copyright (c) 2014 abel533@gmail.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -package com.isea533.mybatis.pagehelper; - -import org.apache.ibatis.session.RowBounds; - -import java.util.ArrayList; -import java.util.List; - -/** - * Mybatis - 分页对象 - * - * @author liuzh/abel533/isea533 - * @version 3.3.0 - * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper - */ -public class Page extends ArrayList { - private static final long serialVersionUID = 1L; - - /**不进行count查询*/ - private static final int NO_SQL_COUNT = -1; - /**进行count查询*/ - private static final int SQL_COUNT = 0; - /**页码,从1开始*/ - private int pageNum; - /**页面大小*/ - private int pageSize; - /**起始行*/ - private int startRow; - /**末行*/ - private int endRow; - /**总数*/ - private long total; - /**总页数*/ - private int pages; - /**分页合理化*/ - private boolean reasonable; - - public Page(){ - super(); - } - - public Page(int pageNum, int pageSize) { - this(pageNum, pageSize, SQL_COUNT); - } - - public Page(int pageNum, int pageSize, boolean count) { - this(pageNum, pageSize, count ? Page.SQL_COUNT : Page.NO_SQL_COUNT); - } - - public Page(int pageNum, int pageSize, int total) { - super(pageSize > -1 ? pageSize : 0); - this.pageNum = pageNum; - this.pageSize = pageSize; - this.total = total; - calculateStartAndEndRow(); - } - - public Page(RowBounds rowBounds, boolean count) { - this(rowBounds, count ? Page.SQL_COUNT : Page.NO_SQL_COUNT); - } - - - public Page(RowBounds rowBounds, int total) { - super(rowBounds.getLimit() > -1 ? rowBounds.getLimit() : 0); - this.pageSize = rowBounds.getLimit(); - this.startRow = rowBounds.getOffset(); - //RowBounds方式默认不求count总数,如果想求count,可以修改这里为SQL_COUNT - this.total = total; - this.endRow = this.startRow + this.pageSize; - } - - public List getResult() { - return this; - } - - public int getPages() { - return pages; - } - - public int getEndRow() { - return endRow; - } - - public int getPageNum() { - return pageNum; - } - - public void setPageNum(int pageNum) { - //分页合理化,针对不合理的页码自动处理 - this.pageNum = (reasonable && pageNum <= 0) ? 1 : pageNum; - } - - public int getPageSize() { - return pageSize; - } - - public void setPageSize(int pageSize) { - this.pageSize = pageSize; - } - - public int getStartRow() { - return startRow; - } - - public long getTotal() { - return total; - } - - public void setTotal(long total) { - this.total = total; - if (pageSize > 0) { - pages = (int) (total / pageSize + ((total % pageSize == 0) ? 0 : 1)); - } else { - pages = 0; - } - //分页合理化,针对不合理的页码自动处理 - if (reasonable && pageNum > pages) { - pageNum = pages; - calculateStartAndEndRow(); - } - } - - public void setReasonable(boolean reasonable) { - this.reasonable = reasonable; - //分页合理化,针对不合理的页码自动处理 - if (this.reasonable && this.pageNum <= 0) { - this.pageNum = 1; - calculateStartAndEndRow(); - } - } - - /** - * 计算起止行号 - */ - private void calculateStartAndEndRow() { - this.startRow = this.pageNum > 0 ? (this.pageNum - 1) * this.pageSize : 0; - this.endRow = this.startRow + this.pageSize * (this.pageNum > 0 ? 1 : 0); - } - - public boolean isCount() { - return this.total > NO_SQL_COUNT; - } - - @Override - public String toString() { - return "Page{" + - "pageNum=" + pageNum + - ", pageSize=" + pageSize + - ", startRow=" + startRow + - ", endRow=" + endRow + - ", total=" + total + - ", pages=" + pages + - '}'; - } -} diff --git a/src/main/java/com/isea533/mybatis/pagehelper/PageHelper.java b/src/main/java/com/isea533/mybatis/pagehelper/PageHelper.java deleted file mode 100644 index adbf803..0000000 --- a/src/main/java/com/isea533/mybatis/pagehelper/PageHelper.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - The MIT License (MIT) - - Copyright (c) 2014 abel533@gmail.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -package com.isea533.mybatis.pagehelper; - -import org.apache.ibatis.executor.Executor; -import org.apache.ibatis.mapping.BoundSql; -import org.apache.ibatis.mapping.MappedStatement; -import org.apache.ibatis.plugin.*; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; - -import java.util.List; -import java.util.Properties; - -/** - * Mybatis - 通用分页拦截器 - * - * @author liuzh/abel533/isea533 - * @version 3.3.0 - * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper - */ -@SuppressWarnings({"rawtypes", "unchecked"}) -@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})) -public class PageHelper implements Interceptor { - private static final ThreadLocal LOCAL_PAGE = new ThreadLocal(); - //sql工具类 - private SqlUtil SQLUTIL; - //RowBounds参数offset作为PageNum使用 - 默认不使用 - private boolean offsetAsPageNum = false; - //RowBounds是否进行count查询 - 默认不查询 - private boolean rowBoundsWithCount = false; - //当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页 - private boolean pageSizeZero = false; - //分页合理化 - private boolean reasonable = false; - /** - * 开始分页 - * - * @param pageNum 页码 - * @param pageSize 每页显示数量 - */ - public static void startPage(int pageNum, int pageSize) { - startPage(pageNum, pageSize, true); - } - - /** - * 开始分页 - * - * @param pageNum 页码 - * @param pageSize 每页显示数量 - * @param count 是否进行count查询 - */ - public static void startPage(int pageNum, int pageSize, boolean count) { - LOCAL_PAGE.set(new Page(pageNum, pageSize, count)); - } - - /** - * 获取分页参数 - * - * @param rowBounds RowBounds参数 - * @return 返回Page对象 - */ - private Page getPage(RowBounds rowBounds) { - Page page = LOCAL_PAGE.get(); - //移除本地变量 - LOCAL_PAGE.remove(); - if (page == null) { - if (offsetAsPageNum) { - page = new Page(rowBounds.getOffset(), rowBounds.getLimit(), rowBoundsWithCount); - } else { - page = new Page(rowBounds, rowBoundsWithCount); - } - } - //分页合理化 - page.setReasonable(reasonable); - return page; - } - - /** - * Mybatis拦截器方法 - * - * @param invocation 拦截器入参 - * @return 返回执行结果 - * @throws Throwable 抛出异常 - */ - public Object intercept(Invocation invocation) throws Throwable { - final Object[] args = invocation.getArgs(); - RowBounds rowBounds = (RowBounds) args[2]; - if (LOCAL_PAGE.get() == null && rowBounds == RowBounds.DEFAULT) { - return invocation.proceed(); - } else { - //忽略RowBounds-否则会进行Mybatis自带的内存分页 - args[2] = RowBounds.DEFAULT; - MappedStatement ms = (MappedStatement) args[0]; - Object parameterObject = args[1]; - //分页信息 - Page page = getPage(rowBounds); - //pageSizeZero的判断 - if (pageSizeZero && page.getPageSize() == 0) { - //执行正常(不分页)查询 - Object result = invocation.proceed(); - //得到处理结果 - page.addAll((List) result); - //相当于查询第一页 - page.setPageNum(1); - //这种情况相当于pageSize=total - page.setPageSize(page.size()); - //仍然要设置total - page.setTotal(page.size()); - //返回结果仍然为Page类型 - 便于后面对接收类型的统一处理 - return page; - } - //简单的通过total的值来判断是否进行count查询 - if (page.isCount()) { - BoundSql boundSql = null; - //只有静态sql需要获取boundSql - if (!SQLUTIL.isDynamic(ms)) { - boundSql = ms.getBoundSql(parameterObject); - } - //将参数中的MappedStatement替换为新的qs - args[0] = SQLUTIL.getCountMappedStatement(ms, boundSql); - //查询总数 - Object result = invocation.proceed(); - //设置总数 - page.setTotal((Integer) ((List) result).get(0)); - if (page.getTotal() == 0) { - return page; - } - } - //pageSize>0的时候执行分页查询,pageSize<=0的时候不执行相当于可能只返回了一个count - if (page.getPageSize() > 0 && - ((rowBounds == RowBounds.DEFAULT && page.getPageNum() > 0) - || rowBounds != RowBounds.DEFAULT)) { - BoundSql boundSql = null; - //只有静态sql需要获取boundSql - if (!SQLUTIL.isDynamic(ms)) { - boundSql = ms.getBoundSql(parameterObject); - } - //将参数中的MappedStatement替换为新的qs - args[0] = SQLUTIL.getPageMappedStatement(ms, boundSql); - //动态sql时,boundSql在这儿通过新的ms获取 - if (boundSql == null) { - boundSql = ((MappedStatement) args[0]).getBoundSql(parameterObject); - } - //判断parameterObject,然后赋值 - args[1] = SQLUTIL.setPageParameter(ms, parameterObject, boundSql, page); - //执行分页查询 - Object result = invocation.proceed(); - //得到处理结果 - page.addAll((List) result); - } - //返回结果 - return page; - } - } - - /** - * 只拦截Executor - * - * @param target - * @return - */ - public Object plugin(Object target) { - if (target instanceof Executor) { - return Plugin.wrap(target, this); - } else { - return target; - } - } - - /** - * 设置属性值 - * - * @param p 属性值 - */ - public void setProperties(Properties p) { - //数据库方言 - String dialect = p.getProperty("dialect"); - SQLUTIL = new SqlUtil(dialect); - //offset作为PageNum使用 - String offsetAsPageNum = p.getProperty("offsetAsPageNum"); - this.offsetAsPageNum = Boolean.parseBoolean(offsetAsPageNum); - //RowBounds方式是否做count查询 - String rowBoundsWithCount = p.getProperty("rowBoundsWithCount"); - this.rowBoundsWithCount = Boolean.parseBoolean(rowBoundsWithCount); - //当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页 - String pageSizeZero = p.getProperty("pageSizeZero"); - this.pageSizeZero = Boolean.parseBoolean(pageSizeZero); - //分页合理化,true开启,如果分页参数不合理会自动修正。默认false不启用 - String reasonable = p.getProperty("reasonable"); - this.reasonable = Boolean.parseBoolean(reasonable); - } -} diff --git a/src/main/java/com/isea533/mybatis/pagehelper/PageInfo.java b/src/main/java/com/isea533/mybatis/pagehelper/PageInfo.java deleted file mode 100644 index d5a6930..0000000 --- a/src/main/java/com/isea533/mybatis/pagehelper/PageInfo.java +++ /dev/null @@ -1,272 +0,0 @@ -package com.isea533.mybatis.pagehelper; - -import java.util.List; - -/** - * 对Page结果进行包装 - *

- * 新增分页的多项属性,主要参考:http://bbs.csdn.net/topics/360010907 - * - * @author liuzh/abel533/isea533 - * @version 3.3.0 - * @since 3.2.2 - * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper - */ -@SuppressWarnings({ "rawtypes", "unchecked" }) -public class PageInfo { - //当前页 - private int pageNum; - //每页的数量 - private int pageSize; - //当前页的数量 - private int size; - //由于startRow和endRow不常用,这里说个具体的用法 - //可以在页面中"显示startRow到endRow 共size条数据" - - //当前页面第一个元素在数据库中的行号 - private int startRow; - //当前页面最后一个元素在数据库中的行号 - private int endRow; - //总记录数 - private long total; - //总页数 - private int pages; - //结果集 - private List list; - - //第一页 - private int firstPage; - //前一页 - private int prePage; - //下一页 - private int nextPage; - //最后一页 - private int lastPage; - - //是否为第一页 - private boolean isFirstPage = false; - //是否为最后一页 - private boolean isLastPage = false; - //是否有前一页 - private boolean hasPreviousPage = false; - //是否有下一页 - private boolean hasNextPage = false; - //导航页码数 - private int navigatePages; - //所有导航页号 - private int[] navigatepageNums; - - /** - * 包装Page对象 - * - * @param list - */ - public PageInfo(List list) { - this(list, 8); - } - - /** - * 包装Page对象 - * - * @param list page结果 - * @param navigatePages 页码数量 - */ - public PageInfo(List list, int navigatePages) { - if (list instanceof Page) { - Page page = (Page) list; - this.pageNum = page.getPageNum(); - this.pageSize = page.getPageSize(); - - this.total = page.getTotal(); - this.pages = page.getPages(); - this.list = page; - this.size = page.size(); - //由于结果是>startRow的,所以实际的需要+1 - if (this.size == 0) { - this.startRow = 0; - this.endRow = 0; - } else { - this.startRow = page.getStartRow() + 1; - //计算实际的endRow(最后一页的时候特殊) - this.endRow = this.startRow - 1 + this.size; - } - this.navigatePages = navigatePages; - //计算导航页 - calcNavigatepageNums(); - //计算前后页,第一页,最后一页 - calcPage(); - //判断页面边界 - judgePageBoudary(); - } - } - - /** - * 计算导航页 - */ - private void calcNavigatepageNums() { - //当总页数小于或等于导航页码数时 - if (pages <= navigatePages) { - navigatepageNums = new int[pages]; - for (int i = 0; i < pages; i++) { - navigatepageNums[i] = i + 1; - } - } else { //当总页数大于导航页码数时 - navigatepageNums = new int[navigatePages]; - int startNum = pageNum - navigatePages / 2; - int endNum = pageNum + navigatePages / 2; - - if (startNum < 1) { - startNum = 1; - //(最前navigatePages页 - for (int i = 0; i < navigatePages; i++) { - navigatepageNums[i] = startNum++; - } - } else if (endNum > pages) { - endNum = pages; - //最后navigatePages页 - for (int i = navigatePages - 1; i >= 0; i--) { - navigatepageNums[i] = endNum--; - } - } else { - //所有中间页 - for (int i = 0; i < navigatePages; i++) { - navigatepageNums[i] = startNum++; - } - } - } - } - - /** - * 计算前后页,第一页,最后一页 - */ - private void calcPage() { - if (navigatepageNums != null && navigatepageNums.length > 0) { - firstPage = navigatepageNums[0]; - lastPage = navigatepageNums[navigatepageNums.length - 1]; - if (pageNum > 1) { - prePage = pageNum - 1; - } - if (pageNum < pages) { - nextPage = pageNum + 1; - } - } - } - - /** - * 判定页面边界 - */ - private void judgePageBoudary() { - isFirstPage = pageNum == 1; - isLastPage = pageNum == pages && pageNum != 1; - hasPreviousPage = pageNum > 1; - hasNextPage = pageNum < pages; - } - - public void setPageNum(int pageNum) { - this.pageNum = pageNum; - } - - public int getPageNum() { - return pageNum; - } - - public int getPageSize() { - return pageSize; - } - - public int getSize() { - return size; - } - - public int getStartRow() { - return startRow; - } - - public int getEndRow() { - return endRow; - } - - public long getTotal() { - return total; - } - - public int getPages() { - return pages; - } - - public List getList() { - return list; - } - - public int getFirstPage() { - return firstPage; - } - - public int getPrePage() { - return prePage; - } - - public int getNextPage() { - return nextPage; - } - - public int getLastPage() { - return lastPage; - } - - public boolean isIsFirstPage() { - return isFirstPage; - } - - public boolean isIsLastPage() { - return isLastPage; - } - - public boolean isHasPreviousPage() { - return hasPreviousPage; - } - - public boolean isHasNextPage() { - return hasNextPage; - } - - public int getNavigatePages() { - return navigatePages; - } - - public int[] getNavigatepageNums() { - return navigatepageNums; - } - - @Override - public String toString() { - final StringBuffer sb = new StringBuffer("PageInfo{"); - sb.append("pageNum=").append(pageNum); - sb.append(", pageSize=").append(pageSize); - sb.append(", size=").append(size); - sb.append(", startRow=").append(startRow); - sb.append(", endRow=").append(endRow); - sb.append(", total=").append(total); - sb.append(", pages=").append(pages); - sb.append(", list=").append(list); - sb.append(", firstPage=").append(firstPage); - sb.append(", prePage=").append(prePage); - sb.append(", nextPage=").append(nextPage); - sb.append(", lastPage=").append(lastPage); - sb.append(", isFirstPage=").append(isFirstPage); - sb.append(", isLastPage=").append(isLastPage); - sb.append(", hasPreviousPage=").append(hasPreviousPage); - sb.append(", hasNextPage=").append(hasNextPage); - sb.append(", navigatePages=").append(navigatePages); - sb.append(", navigatepageNums="); - if (navigatepageNums == null) sb.append("null"); - else { - sb.append('['); - for (int i = 0; i < navigatepageNums.length; ++i) - sb.append(i == 0 ? "" : ", ").append(navigatepageNums[i]); - sb.append(']'); - } - sb.append('}'); - return sb.toString(); - } -} diff --git a/src/main/java/com/isea533/mybatis/pagehelper/SqlParser.java b/src/main/java/com/isea533/mybatis/pagehelper/SqlParser.java deleted file mode 100644 index a46694b..0000000 --- a/src/main/java/com/isea533/mybatis/pagehelper/SqlParser.java +++ /dev/null @@ -1,242 +0,0 @@ -package com.isea533.mybatis.pagehelper; - -import net.sf.jsqlparser.JSQLParserException; -import net.sf.jsqlparser.expression.Alias; -import net.sf.jsqlparser.parser.CCJSqlParserUtil; -import net.sf.jsqlparser.schema.Column; -import net.sf.jsqlparser.statement.Statement; -import net.sf.jsqlparser.statement.select.*; -import org.apache.ibatis.mapping.BoundSql; -import org.apache.ibatis.mapping.MappedStatement; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * sql解析类,使用该类时,必须引入jsqlparser-x.x.x.jar - * - * @author liuzh - */ -@SuppressWarnings("rawtypes") -public class SqlParser implements SqlUtil.Parser { - private static final List COUNT_ITEM; - private static final Alias TABLE_ALIAS; - private SqlUtil.Parser simpleParser; - - static { - COUNT_ITEM = new ArrayList(); - COUNT_ITEM.add(new SelectExpressionItem(new Column("count(*)"))); - - TABLE_ALIAS = new Alias("table_count"); - TABLE_ALIAS.setUseAs(false); - } - - //缓存已经修改过的sql - private Map CACHE = new ConcurrentHashMap(); - - public SqlParser(SqlUtil.Dialect dialect) { - simpleParser = SqlUtil.SimpleParser.newParser(dialect); - } - - public void isSupportedSql(String sql) { - simpleParser.isSupportedSql(sql); - } - - public String getCountSql(String sql) { - //校验是否支持该sql - isSupportedSql(sql); - return parse(sql); - } - - public String getPageSql(String sql) { - return simpleParser.getPageSql(sql); - } - - public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) { - return simpleParser.setPageParameter(ms, parameterObject, boundSql, page); - } - - public String parse(String sql) { - if (CACHE.get(sql) != null) { - return CACHE.get(sql); - } - Statement stmt = null; - try { - stmt = CCJSqlParserUtil.parse(sql); - } catch (JSQLParserException e) { - //无法解析的直接返回原sql - CACHE.put(sql, sql); - return sql; - } - Select select = (Select) stmt; - SelectBody selectBody = select.getSelectBody(); - //处理body - processSelectBody(selectBody); - //处理with - processWithItemsList(select.getWithItemsList()); - //处理为count查询 - sqlToCount(select); - String result = select.toString(); - CACHE.put(sql, result); - return result; - } - - /** - * 将sql转换为count查询 - * - * @param select - */ - public void sqlToCount(Select select) { - SelectBody selectBody = select.getSelectBody(); - // select中包含参数时在else中处理 - // select中包含group by时在else中处理 - if (selectBody instanceof PlainSelect - && !selectItemsHashParameters(((PlainSelect) selectBody).getSelectItems()) - && ((PlainSelect) selectBody).getGroupByColumnReferences() == null) { - ((PlainSelect) selectBody).setSelectItems(COUNT_ITEM); - } else { - PlainSelect plainSelect = new PlainSelect(); - SubSelect subSelect = new SubSelect(); - subSelect.setSelectBody(selectBody); - subSelect.setAlias(TABLE_ALIAS); - plainSelect.setFromItem(subSelect); - plainSelect.setSelectItems(COUNT_ITEM); - select.setSelectBody(plainSelect); - } - } - - /** - * 处理selectBody去除Order by - * - * @param selectBody - */ - public void processSelectBody(SelectBody selectBody) { - if (selectBody instanceof PlainSelect) { - processPlainSelect((PlainSelect) selectBody); - } else if (selectBody instanceof WithItem) { - WithItem withItem = (WithItem) selectBody; - if (withItem.getSelectBody() != null) { - processSelectBody(withItem.getSelectBody()); - } - } else { - SetOperationList operationList = (SetOperationList) selectBody; - if (operationList.getPlainSelects() != null && operationList.getPlainSelects().size() > 0) { - List plainSelects = operationList.getPlainSelects(); - for (PlainSelect plainSelect : plainSelects) { - processPlainSelect(plainSelect); - } - } - if (!orderByHashParameters(operationList.getOrderByElements())) { - operationList.setOrderByElements(null); - } - } - } - - /** - * 处理PlainSelect类型的selectBody - * - * @param plainSelect - */ - public void processPlainSelect(PlainSelect plainSelect) { - if (!orderByHashParameters(plainSelect.getOrderByElements())) { - plainSelect.setOrderByElements(null); - } - if (plainSelect.getFromItem() != null) { - processFromItem(plainSelect.getFromItem()); - } - if (plainSelect.getJoins() != null && plainSelect.getJoins().size() > 0) { - List joins = plainSelect.getJoins(); - for (Join join : joins) { - if (join.getRightItem() != null) { - processFromItem(join.getRightItem()); - } - } - } - } - - /** - * 处理WithItem - * - * @param withItemsList - */ - public void processWithItemsList(List withItemsList) { - if (withItemsList != null && withItemsList.size() > 0) { - for (WithItem item : withItemsList) { - processSelectBody(item.getSelectBody()); - } - } - } - - /** - * 处理子查询 - * - * @param fromItem - */ - public void processFromItem(FromItem fromItem) { - if (fromItem instanceof SubJoin) { - SubJoin subJoin = (SubJoin) fromItem; - if (subJoin.getJoin() != null) { - if (subJoin.getJoin().getRightItem() != null) { - processFromItem(subJoin.getJoin().getRightItem()); - } - } - if (subJoin.getLeft() != null) { - processFromItem(subJoin.getLeft()); - } - } else if (fromItem instanceof SubSelect) { - SubSelect subSelect = (SubSelect) fromItem; - if (subSelect.getSelectBody() != null) { - processSelectBody(subSelect.getSelectBody()); - } - } else if (fromItem instanceof ValuesList) { - - } else if (fromItem instanceof LateralSubSelect) { - LateralSubSelect lateralSubSelect = (LateralSubSelect) fromItem; - if (lateralSubSelect.getSubSelect() != null) { - SubSelect subSelect = (SubSelect) (lateralSubSelect.getSubSelect()); - if (subSelect.getSelectBody() != null) { - processSelectBody(subSelect.getSelectBody()); - } - } - } - //Table时不用处理 - } - - /** - * 判断Orderby是否包含参数,有参数的不能去 - * - * @param orderByElements - * @return - */ - public boolean orderByHashParameters(List orderByElements) { - if (orderByElements == null) { - return false; - } - for (OrderByElement orderByElement : orderByElements) { - if (orderByElement.toString().contains("?")) { - return true; - } - } - return false; - } - - /** - * 判断selectItems是否包含参数,有参数的不能去 - * - * @param selectItems - * @return - */ - public boolean selectItemsHashParameters(List selectItems) { - if (selectItems == null) { - return false; - } - for (SelectItem selectItem : selectItems) { - if (selectItem.toString().contains("?")) { - return true; - } - } - return false; - } -} diff --git a/src/main/java/com/isea533/mybatis/pagehelper/SqlUtil.java b/src/main/java/com/isea533/mybatis/pagehelper/SqlUtil.java deleted file mode 100644 index b603b25..0000000 --- a/src/main/java/com/isea533/mybatis/pagehelper/SqlUtil.java +++ /dev/null @@ -1,549 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2014 abel533@gmail.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.isea533.mybatis.pagehelper; - -import org.apache.ibatis.builder.SqlSourceBuilder; -import org.apache.ibatis.mapping.*; -import org.apache.ibatis.reflection.MetaObject; -import org.apache.ibatis.reflection.factory.DefaultObjectFactory; -import org.apache.ibatis.reflection.factory.ObjectFactory; -import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; -import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory; -import org.apache.ibatis.scripting.xmltags.DynamicContext; -import org.apache.ibatis.scripting.xmltags.DynamicSqlSource; -import org.apache.ibatis.scripting.xmltags.MixedSqlNode; -import org.apache.ibatis.scripting.xmltags.SqlNode; -import org.apache.ibatis.session.Configuration; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Mybatis - sql工具,获取分页和count的MappedStatement,设置分页参数 - * - * @author liuzh/abel533/isea533 - * @since 3.3.0 - * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper - */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class SqlUtil { - private static final List EMPTY_RESULTMAPPING = new ArrayList(0); - //分页的id后缀 - private static final String SUFFIX_PAGE = "_PageHelper"; - //count查询的id后缀 - private static final String SUFFIX_COUNT = SUFFIX_PAGE + "_Count"; - //第一个分页参数 - private static final String PAGEPARAMETER_FIRST = "First" + SUFFIX_PAGE; - //第二个分页参数 - private static final String PAGEPARAMETER_SECOND = "Second" + SUFFIX_PAGE; - - private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory(); - private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory(); - - /** - * 反射对象,增加对低版本Mybatis的支持 - * - * @param object 反射对象 - * @return - */ - private static MetaObject forObject(Object object) { - return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY); - } - - private SqlUtil.Parser sqlParser; - - //数据库方言 - 使用枚举限制数据库类型 - public enum Dialect { - mysql, mariadb, sqlite, oracle, hsqldb, postgresql - } - - /** - * 构造方法 - * - * @param strDialect - */ - public SqlUtil(String strDialect) { - if (strDialect == null || "".equals(strDialect)) { - throw new IllegalArgumentException("Mybatis分页插件无法获取dialect参数!"); - } - try { - Dialect dialect = Dialect.valueOf(strDialect); - String sqlParserClass = this.getClass().getPackage().getName() + ".SqlParser"; - try { - //使用SqlParser必须引入jsqlparser-x.x.x.jar - Class.forName("net.sf.jsqlparser.statement.select.Select"); - sqlParser = (Parser) Class.forName(sqlParserClass).getConstructor(Dialect.class).newInstance(dialect); - } catch (Exception e) { - //找不到时,不用处理 - } - if (sqlParser == null) { - sqlParser = SimpleParser.newParser(dialect); - } - } catch (IllegalArgumentException e) { - String dialects = null; - for (Dialect d : Dialect.values()) { - if (dialects == null) { - dialects = d.toString(); - } else { - dialects += "," + d; - } - } - throw new IllegalArgumentException("Mybatis分页插件dialect参数值错误,可选值为[" + dialects + "]"); - } - } - - /** - * 设置分页参数 - * - * @param parameterObject - * @param boundSql - * @param page - * @return - */ - public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) { - return sqlParser.setPageParameter(ms, parameterObject, boundSql, page); - } - - /** - * 获取count查询的MappedStatement - * - * @param ms - * @param boundSql - * @return - */ - public MappedStatement getCountMappedStatement(MappedStatement ms, BoundSql boundSql) { - return getMappedStatement(ms, boundSql, SUFFIX_COUNT); - } - - /** - * 获取分页查询的MappedStatement - * - * @param ms - * @param boundSql - * @return - */ - public MappedStatement getPageMappedStatement(MappedStatement ms, BoundSql boundSql) { - return getMappedStatement(ms, boundSql, SUFFIX_PAGE); - } - - /** - * 处理SQL - */ - public static interface Parser { - void isSupportedSql(String sql); - - String getCountSql(String sql); - - String getPageSql(String sql); - - Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page); - } - - public static abstract class SimpleParser implements Parser { - public static Parser newParser(Dialect dialect) { - Parser parser = null; - switch (dialect) { - case mysql: - case mariadb: - case sqlite: - parser = new MysqlParser(); - break; - case oracle: - parser = new OracleParser(); - break; - case hsqldb: - parser = new HsqldbParser(); - break; - case postgresql: - default: - parser = new PostgreSQLParser(); - } - return parser; - } - - public void isSupportedSql(String sql) { - if (sql.trim().toUpperCase().endsWith("FOR UPDATE")) { - throw new RuntimeException("分页插件不支持包含for update的sql"); - } - } - - /** - * 获取总数sql - 如果要支持其他数据库,修改这里就可以 - * - * @param sql 原查询sql - * @return 返回count查询sql - */ - public String getCountSql(final String sql) { - isSupportedSql(sql); - StringBuilder stringBuilder = new StringBuilder(sql.length() + 40); - stringBuilder.append("select count(*) from ("); - stringBuilder.append(sql); - stringBuilder.append(") tmp_count"); - return stringBuilder.toString(); - } - - /** - * 获取分页sql - 如果要支持其他数据库,修改这里就可以 - * - * @param sql 原查询sql - * @return 返回分页sql - */ - public abstract String getPageSql(String sql); - - public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) { - Map paramMap = null; - if (parameterObject == null) { - paramMap = new HashMap(); - } else if (parameterObject instanceof Map) { - paramMap = (Map) parameterObject; - } else { - paramMap = new HashMap(); - //动态sql时的判断条件不会出现在ParameterMapping中,但是必须有,所以这里需要收集所有的getter属性 - //TypeHandlerRegistry可以直接处理的会作为一个直接使用的对象进行处理 - boolean hasTypeHandler = ms.getConfiguration().getTypeHandlerRegistry().hasTypeHandler(parameterObject.getClass()); - if (!hasTypeHandler) { - MetaObject metaObject = forObject(parameterObject); - for (String name : metaObject.getGetterNames()) { - paramMap.put(name, metaObject.getValue(name)); - } - } - //下面这段方法,主要解决一个常见类型的参数时的问题 - if (boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0) { - for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) { - String name = parameterMapping.getProperty(); - if (!name.equals(PAGEPARAMETER_FIRST) - && !name.equals(PAGEPARAMETER_SECOND) - && paramMap.get(name) == null) { - if (hasTypeHandler - || parameterMapping.getJavaType().isAssignableFrom(parameterObject.getClass())) { - paramMap.put(name, parameterObject); - } - } - } - } - } - return paramMap; - } - } - - //Mysql - private static class MysqlParser extends SimpleParser { - @Override - public String getPageSql(String sql) { - StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14); - sqlBuilder.append(sql); - sqlBuilder.append(" limit ?,?"); - return sqlBuilder.toString(); - } - - @Override - public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) { - Map paramMap = super.setPageParameter(ms, parameterObject, boundSql, page); - paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow()); - paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize()); - return paramMap; - } - } - - //Oracle - private static class OracleParser extends SimpleParser { - @Override - public String getPageSql(String sql) { - StringBuilder sqlBuilder = new StringBuilder(sql.length() + 120); - sqlBuilder.append("select * from ( select tmp_page.*, rownum row_id from ( "); - sqlBuilder.append(sql); - sqlBuilder.append(" ) tmp_page where rownum <= ? ) where row_id > ?"); - return sqlBuilder.toString(); - } - - @Override - public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) { - Map paramMap = super.setPageParameter(ms, parameterObject, boundSql, page); - paramMap.put(PAGEPARAMETER_FIRST, page.getEndRow()); - paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); - return paramMap; - } - } - - //Oracle - private static class HsqldbParser extends SimpleParser { - @Override - public String getPageSql(String sql) { - StringBuilder sqlBuilder = new StringBuilder(sql.length() + 20); - sqlBuilder.append(sql); - sqlBuilder.append(" limit ? offset ?"); - return sqlBuilder.toString(); - } - - @Override - public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) { - Map paramMap = super.setPageParameter(ms, parameterObject, boundSql, page); - paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize()); - paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); - return paramMap; - } - } - - //PostgreSQL - private static class PostgreSQLParser extends SimpleParser { - @Override - public String getPageSql(String sql) { - StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14); - sqlBuilder.append(sql); - sqlBuilder.append(" limit ? offset ?"); - return sqlBuilder.toString(); - } - - @Override - public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) { - Map paramMap = super.setPageParameter(ms, parameterObject, boundSql, page); - paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize()); - paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); - return paramMap; - } - } - - /** - * 自定义简单SqlSource - */ - private class BoundSqlSqlSource implements SqlSource { - BoundSql boundSql; - - public BoundSqlSqlSource(BoundSql boundSql) { - this.boundSql = boundSql; - } - - public BoundSql getBoundSql(Object parameterObject) { - return boundSql; - } - - public BoundSql getBoundSql() { - return boundSql; - } - } - - /** - * 自定义动态SqlSource - */ - private class MyDynamicSqlSource implements SqlSource { - private Configuration configuration; - private SqlNode rootSqlNode; - /** - * 用于区分动态的count查询或分页查询 - */ - private Boolean count; - - public MyDynamicSqlSource(Configuration configuration, SqlNode rootSqlNode, Boolean count) { - this.configuration = configuration; - this.rootSqlNode = rootSqlNode; - this.count = count; - } - - public BoundSql getBoundSql(Object parameterObject) { - DynamicContext context = new DynamicContext(configuration, parameterObject); - rootSqlNode.apply(context); - SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration); - Class parameterType = parameterObject == null ? Object.class : parameterObject.getClass(); - SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings()); - BoundSql boundSql = sqlSource.getBoundSql(parameterObject); - //设置条件参数 - for (Map.Entry entry : context.getBindings().entrySet()) { - boundSql.setAdditionalParameter(entry.getKey(), entry.getValue()); - } - BoundSqlSqlSource boundSqlSqlSource = new BoundSqlSqlSource(boundSql); - if (count) { - boundSqlSqlSource = getCountSqlSource(boundSqlSqlSource); - } else { - boundSqlSqlSource = getPageSqlSource(configuration, boundSqlSqlSource); - } - return boundSqlSqlSource.getBoundSql(); - } - } - - - /** - * 获取ms - 在这里对新建的ms做了缓存,第一次新增,后面都会使用缓存值 - * - * @param ms - * @param boundSql - * @param suffix - * @return - */ - private MappedStatement getMappedStatement(MappedStatement ms, BoundSql boundSql, String suffix) { - MappedStatement qs = null; - try { - qs = ms.getConfiguration().getMappedStatement(ms.getId() + suffix); - } catch (Exception e) { - //ignore - } - if (qs == null) { - //创建一个新的MappedStatement - qs = newMappedStatement(ms, getNewSqlSource(ms, new BoundSqlSqlSource(boundSql), suffix), suffix); - try { - ms.getConfiguration().addMappedStatement(qs); - } catch (Exception e) { - //ignore - } - } - return qs; - } - - /** - * 新建count查询和分页查询的MappedStatement - * - * @param ms - * @param newSqlSource - * @param suffix - * @return - */ - private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource, String suffix) { - String id = ms.getId() + suffix; - MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), id, newSqlSource, ms.getSqlCommandType()); - builder.resource(ms.getResource()); - builder.fetchSize(ms.getFetchSize()); - builder.statementType(ms.getStatementType()); - builder.keyGenerator(ms.getKeyGenerator()); - if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) { - StringBuilder keyProperties = new StringBuilder(); - for (String keyProperty : ms.getKeyProperties()) { - keyProperties.append(keyProperty).append(","); - } - keyProperties.delete(keyProperties.length() - 1, keyProperties.length()); - builder.keyProperty(keyProperties.toString()); - } - builder.timeout(ms.getTimeout()); - builder.parameterMap(ms.getParameterMap()); - if (suffix == SUFFIX_PAGE) { - builder.resultMaps(ms.getResultMaps()); - } else { - //count查询返回值int - List resultMaps = new ArrayList(); - ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), id, int.class, EMPTY_RESULTMAPPING).build(); - resultMaps.add(resultMap); - builder.resultMaps(resultMaps); - } - builder.resultSetType(ms.getResultSetType()); - builder.cache(ms.getCache()); - builder.flushCacheRequired(ms.isFlushCacheRequired()); - builder.useCache(ms.isUseCache()); - - return builder.build(); - } - - /** - * 判断当前执行的是否为动态sql - * - * @param ms - * @return - */ - public boolean isDynamic(MappedStatement ms) { - return ms.getSqlSource() instanceof DynamicSqlSource; - } - - /** - * 获取新的sqlSource - * - * @param ms - * @param newSqlSource - * @param suffix - * @return - */ - private SqlSource getNewSqlSource(MappedStatement ms, BoundSqlSqlSource newSqlSource, String suffix) { - //从XMLLanguageDriver.java和XMLScriptBuilder.java可以看出只有两种SqlSource - //如果是动态sql - if (isDynamic(ms)) { - MetaObject msObject = forObject(ms); - SqlNode sqlNode = (SqlNode) msObject.getValue("sqlSource.rootSqlNode"); - MixedSqlNode mixedSqlNode = null; - if (sqlNode instanceof MixedSqlNode) { - mixedSqlNode = (MixedSqlNode) sqlNode; - } else { - List contents = new ArrayList(1); - contents.add(sqlNode); - mixedSqlNode = new MixedSqlNode(contents); - } - return new MyDynamicSqlSource(ms.getConfiguration(), mixedSqlNode, suffix == SUFFIX_COUNT); - } - //如果是静态分页sql - else if (suffix == SUFFIX_PAGE) { - //改为分页sql - return getPageSqlSource(ms.getConfiguration(), newSqlSource); - } - //如果是静态count-sql - else { - return getCountSqlSource(newSqlSource); - } - } - - /** - * 获取分页的sqlSource - * - * @param configuration - * @param newSqlSource - * @return - */ - private BoundSqlSqlSource getPageSqlSource(Configuration configuration, BoundSqlSqlSource newSqlSource) { - String sql = newSqlSource.getBoundSql().getSql(); - //改为分页sql - MetaObject sqlObject = forObject(newSqlSource); - sqlObject.setValue("boundSql.sql", sqlParser.getPageSql(sql)); - //添加参数映射 - List newParameterMappings = new ArrayList(); - newParameterMappings.addAll(newSqlSource.getBoundSql().getParameterMappings()); - newParameterMappings.add(new ParameterMapping.Builder(configuration, PAGEPARAMETER_FIRST, Integer.class).build()); - newParameterMappings.add(new ParameterMapping.Builder(configuration, PAGEPARAMETER_SECOND, Integer.class).build()); - sqlObject.setValue("boundSql.parameterMappings", newParameterMappings); - return newSqlSource; - } - - /** - * 获取count的sqlSource - * - * @param newSqlSource - * @return - */ - private BoundSqlSqlSource getCountSqlSource(BoundSqlSqlSource newSqlSource) { - String sql = newSqlSource.getBoundSql().getSql(); - MetaObject sqlObject = forObject(newSqlSource); - sqlObject.setValue("boundSql.sql", sqlParser.getCountSql(sql)); - return newSqlSource; - } - - /** - * 测试[控制台输出]count和分页sql - * - * @param dialet 数据库类型 - * @param originalSql 原sql - */ - public static void testSql(String dialet, String originalSql) { - SqlUtil sqlUtil = new SqlUtil(dialet); - String countSql = sqlUtil.sqlParser.getCountSql(originalSql); - System.out.println(countSql); - String pageSql = sqlUtil.sqlParser.getPageSql(originalSql); - System.out.println(pageSql); - } -} diff --git a/src/main/java/com/isea533/mybatis/service/DemoService.java b/src/main/java/com/isea533/mybatis/service/DemoService.java index 63a952d..a1f0978 100644 --- a/src/main/java/com/isea533/mybatis/service/DemoService.java +++ b/src/main/java/com/isea533/mybatis/service/DemoService.java @@ -1,10 +1,10 @@ package com.isea533.mybatis.service; +import com.github.pagehelper.PageHelper; import com.isea533.mybatis.mapper.Country2Mapper; import com.isea533.mybatis.mapper.CountryMapper; import com.isea533.mybatis.model.Country; import com.isea533.mybatis.model.Country2; -import com.isea533.mybatis.pagehelper.PageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; diff --git a/src/main/resources/applicationContext.xml b/src/main/resources/applicationContext.xml index 4bde1ba..067a72b 100644 --- a/src/main/resources/applicationContext.xml +++ b/src/main/resources/applicationContext.xml @@ -34,7 +34,7 @@ - + dialect=hsqldb @@ -73,14 +73,21 @@ - - + - com.isea533.mybatis.mapperhelper.Mapper + com.github.abel533.mapper.Mapper + + + + + + \ No newline at end of file diff --git a/src/test/java/com/isea533/mybatis/test/BasicTest.java b/src/test/java/com/isea533/mybatis/test/BasicTest.java new file mode 100644 index 0000000..06f465b --- /dev/null +++ b/src/test/java/com/isea533/mybatis/test/BasicTest.java @@ -0,0 +1,13 @@ +package com.isea533.mybatis.test; + +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * Created by liuzh on 2015/3/7. + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:applicationContext.xml") +public class BasicTest { +} diff --git a/src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java b/src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java new file mode 100644 index 0000000..fd6597e --- /dev/null +++ b/src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java @@ -0,0 +1,25 @@ +package com.isea533.mybatis.test; + +import com.isea533.mybatis.mapper.UserInfoMapper; +import org.apache.ibatis.session.SqlSession; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * Created by liuzh on 2015/3/7. + */ +public class NoAutoWiredMapperTest extends BasicTest { + +// @Autowired +// private UserInfoMapper userInfoMapper; + + @Autowired + private SqlSession sqlSession; + + @Test + public void test(){ + UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class); + int count = userInfoMapper.selectCount(null); + System.out.println(count); + } +} diff --git a/src/test/java/com/isea533/mybatis/test/PageEntityMapperTest.java b/src/test/java/com/isea533/mybatis/test/PageEntityMapperTest.java new file mode 100644 index 0000000..4d865e1 --- /dev/null +++ b/src/test/java/com/isea533/mybatis/test/PageEntityMapperTest.java @@ -0,0 +1,30 @@ +package com.isea533.mybatis.test; + +import com.github.abel533.entity.EntityMapper; +import com.github.abel533.entity.Example; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.isea533.mybatis.model.Country; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; + +/** + * Created by liuzh on 2015/3/7. + */ +public class PageEntityMapperTest extends BasicTest { + + @Autowired + private EntityMapper entityMapper; + + @Test + public void test(){ + Example example = new Example(Country.class); + example.createCriteria().andGreaterThan("id",100); + PageHelper.startPage(2,10); + List countries = entityMapper.selectByExample(example); + PageInfo pageInfo = new PageInfo(countries); + System.out.println(pageInfo.getTotal()); + } +} From 887ebb6379286380d2f0e7ffb96117d78401362b Mon Sep 17 00:00:00 2001 From: abel533 Date: Sat, 7 Mar 2015 18:49:04 +0800 Subject: [PATCH 03/10] =?UTF-8?q?=E5=A2=9E=E5=8A=A0EntityMapper=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/applicationContext.xml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/resources/applicationContext.xml b/src/main/resources/applicationContext.xml index 067a72b..b56dffa 100644 --- a/src/main/resources/applicationContext.xml +++ b/src/main/resources/applicationContext.xml @@ -47,7 +47,11 @@ - + + + + + From 4d1ada3311f22e595c628949a155aba254049784 Mon Sep 17 00:00:00 2001 From: abel533 Date: Sat, 7 Mar 2015 18:49:24 +0800 Subject: [PATCH 04/10] =?UTF-8?q?resources=E9=85=8D=E7=BD=AE=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pom.xml b/pom.xml index e84eadc..c338135 100644 --- a/pom.xml +++ b/pom.xml @@ -220,6 +220,9 @@ **/*.xml + + ${basedir}/src/main/resources + From ec3fc3080f665f36e09bd70a474914f0ceebe56e Mon Sep 17 00:00:00 2001 From: abel533 Date: Sat, 7 Mar 2015 20:24:48 +0800 Subject: [PATCH 05/10] =?UTF-8?q?spring=E4=BE=8B=E5=AD=90=E7=9A=84?= =?UTF-8?q?=E9=80=9A=E7=94=A8Mapper=E6=94=B9=E4=B8=BA=E6=8B=A6=E6=88=AA?= =?UTF-8?q?=E5=99=A8=E5=BD=A2=E5=BC=8F=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/applicationContext.xml | 26 +++++++------------ .../mybatis/test/NoAutoWiredMapperTest.java | 3 --- 2 files changed, 9 insertions(+), 20 deletions(-) diff --git a/src/main/resources/applicationContext.xml b/src/main/resources/applicationContext.xml index b56dffa..47cd567 100644 --- a/src/main/resources/applicationContext.xml +++ b/src/main/resources/applicationContext.xml @@ -34,6 +34,15 @@ + + + + mappers=com.github.abel533.mapper.Mapper + IDENTITY=MYSQL + notEmpty=true + + + @@ -77,21 +86,4 @@ - - - - - - com.github.abel533.mapper.Mapper - - - - - - - - - - \ No newline at end of file diff --git a/src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java b/src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java index fd6597e..294dbdd 100644 --- a/src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java +++ b/src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java @@ -10,9 +10,6 @@ */ public class NoAutoWiredMapperTest extends BasicTest { -// @Autowired -// private UserInfoMapper userInfoMapper; - @Autowired private SqlSession sqlSession; From f45314ef35db84e985ad1e74db4df1e3e8a698cb Mon Sep 17 00:00:00 2001 From: isea533 Date: Fri, 10 Apr 2015 11:23:18 +0800 Subject: [PATCH 06/10] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E6=8B=A6=E6=88=AA?= =?UTF-8?q?=E5=99=A8=E9=A1=BA=E5=BA=8F=E9=94=99=E8=AF=AF=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/applicationContext.xml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/resources/applicationContext.xml b/src/main/resources/applicationContext.xml index 47cd567..7301178 100644 --- a/src/main/resources/applicationContext.xml +++ b/src/main/resources/applicationContext.xml @@ -34,20 +34,20 @@ - + - mappers=com.github.abel533.mapper.Mapper - IDENTITY=MYSQL - notEmpty=true + dialect=hsqldb + reasonable=true - + - dialect=hsqldb - reasonable=true + mappers=com.github.abel533.mapper.Mapper + IDENTITY=MYSQL + notEmpty=true From 6886093c9112c2c3c0022aea58a6e051e388a900 Mon Sep 17 00:00:00 2001 From: isea533 Date: Thu, 4 Jun 2015 14:58:22 +0800 Subject: [PATCH 07/10] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E9=80=9A=E7=94=A8Mappe?= =?UTF-8?q?r3.0.0,=E5=88=86=E9=A1=B5=E6=8F=92=E4=BB=B63.7.4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 477 +++++++++--------- .../mybatis/mapper/Country2Mapper.java | 38 -- .../isea533/mybatis/mapper/Country2Mapper.xml | 153 ------ src/main/webapp/WEB-INF/jsp/index.jsp | 16 +- 4 files changed, 246 insertions(+), 438 deletions(-) diff --git a/pom.xml b/pom.xml index c338135..8aaeac0 100644 --- a/pom.xml +++ b/pom.xml @@ -1,247 +1,258 @@ - 4.0.0 - com.isea533 - mybatis-spring - war - 1.0-SNAPSHOT - Spring-Mybatis-Mapper-PageHelper - 这是一个集成了Mybatis分页插件和通用Mapper的示例项目 - http://maven.apache.org + 4.0.0 + com.isea533 + mybatis-spring + war + 1.0-SNAPSHOT + Spring-Mybatis-Mapper-PageHelper + 这是一个集成了Mybatis分页插件和通用Mapper的示例项目 + http://maven.apache.org - - UTF-8 - ${basedir}/src/main/java - - 2.0.1 - 3.6.1 - + + UTF-8 + ${basedir}/src/main/java + + 3.0.0 + 3.7.4 + - - - junit - junit - 4.11 - test - - - log4j - log4j - 1.2.17 - + + + junit + junit + 4.11 + test + + + log4j + log4j + 1.2.17 + - - - javax.servlet - servlet-api - 2.5 - provided - - - javax.servlet.jsp - javax.servlet.jsp-api - 2.3.1 - provided - - - javax.servlet.jsp.jstl - javax.servlet.jsp.jstl-api - 1.2.1 - - - javax.ws.rs - javax.ws.rs-api - 2.0 - - - javax.websocket - javax.websocket-api - 1.0 - - - javax.annotation - javax.annotation-api - 1.2 - - - javax.transaction - javax.transaction-api - 1.2 - + + + javax.servlet + servlet-api + 2.5 + provided + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.1 + provided + + + javax.servlet.jsp.jstl + javax.servlet.jsp.jstl-api + 1.2.1 + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + javax.websocket + javax.websocket-api + 1.0 + + + javax.annotation + javax.annotation-api + 1.2 + + + javax.transaction + javax.transaction-api + 1.2 + - - - org.springframework - spring-context - - - org.springframework - spring-orm - - - org.springframework - spring-oxm - - - org.springframework - spring-jdbc - - - org.springframework - spring-tx - - - org.springframework - spring-web - - - org.springframework - spring-webmvc - - - org.springframework - spring-aop - - - org.springframework - spring-test - + + + org.springframework + spring-context + + + org.springframework + spring-orm + + + org.springframework + spring-oxm + + + org.springframework + spring-jdbc + + + org.springframework + spring-tx + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework + spring-aop + + + org.springframework + spring-test + - - - org.codehaus.castor - castor-xml - 1.3.3 - - - - com.fasterxml.jackson.core - jackson-databind - 2.4.2 - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - 2.4.2 - - - - org.aspectj - aspectjweaver - 1.8.2 - + + + org.codehaus.castor + castor-xml + 1.3.3 + + + + com.fasterxml.jackson.core + jackson-databind + 2.4.2 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + 2.4.2 + + + + org.aspectj + aspectjweaver + 1.8.2 + - - - commons-dbcp - commons-dbcp - 1.4 - - - - commons-fileupload - commons-fileupload - 1.3.1 - + + + commons-dbcp + commons-dbcp + 1.4 + + + + commons-fileupload + commons-fileupload + 1.3.1 + - - - org.hsqldb - hsqldb - 2.2.9 - + + + org.hsqldb + hsqldb + 2.2.9 + - - - org.mybatis - mybatis - 3.2.8 - - - org.mybatis - mybatis-spring - 1.2.2 - - - com.github.jsqlparser - jsqlparser - 0.9.1 - + + + org.mybatis + mybatis + 3.2.8 + + + org.mybatis + mybatis-spring + 1.2.2 + + + com.github.jsqlparser + jsqlparser + 0.9.1 + - - - javax.persistence - persistence-api - 1.0 - + + + javax.persistence + persistence-api + 1.0 + - - - com.github.pagehelper - pagehelper - ${pagehelper.version} - - - - com.github.abel533 - mapper - ${mapper.version} - - - - - - org.springframework - spring-framework-bom - 3.2.12.RELEASE - pom - import - + + + com.github.pagehelper + pagehelper + ${pagehelper.version} + + + + com.github.abel533 + mapper + ${mapper.version} + + + com.github.abel533 + entitymapper + 1.0.0 + + + com.github.abel533 + mapper + + + - - - - nexus - local private nexus - http://maven.oschina.net/content/groups/public/ - - true - - - false - - - - - - - ${basedir}/src/main/java - - **/*.xml - - - - ${basedir}/src/main/resources - - - - - maven-compiler-plugin - - 1.6 - 1.6 - - - - org.mybatis.generator - mybatis-generator-maven-plugin - 1.3.2 - - ${basedir}/src/main/resources/generator.xml - true - true - - - - + + + + org.springframework + spring-framework-bom + 3.2.12.RELEASE + pom + import + + + + + + nexus + local private nexus + http://maven.oschina.net/content/groups/public/ + + true + + + false + + + + + + + ${basedir}/src/main/java + + **/*.xml + + + + ${basedir}/src/main/resources + + + + + maven-compiler-plugin + + 1.6 + 1.6 + + + + org.mybatis.generator + mybatis-generator-maven-plugin + 1.3.2 + + ${basedir}/src/main/resources/generator.xml + true + true + + + + diff --git a/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java b/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java index e27b417..662f681 100644 --- a/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java +++ b/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java @@ -8,43 +8,5 @@ import java.util.List; public interface Country2Mapper extends Mapper { - /** - * This method was generated by MyBatis Generator. - * This method corresponds to the database table country - * - * @mbggenerated Mon Dec 08 11:25:39 CST 2014 - */ - int countByExample(Country2Example example); - /** - * This method was generated by MyBatis Generator. - * This method corresponds to the database table country - * - * @mbggenerated Mon Dec 08 11:25:39 CST 2014 - */ - int deleteByExample(Country2Example example); - - /** - * This method was generated by MyBatis Generator. - * This method corresponds to the database table country - * - * @mbggenerated Mon Dec 08 11:25:39 CST 2014 - */ - List selectByExample(Country2Example example); - - /** - * This method was generated by MyBatis Generator. - * This method corresponds to the database table country - * - * @mbggenerated Mon Dec 08 11:25:39 CST 2014 - */ - int updateByExampleSelective(@Param("record") Country2 record, @Param("example") Country2Example example); - - /** - * This method was generated by MyBatis Generator. - * This method corresponds to the database table country - * - * @mbggenerated Mon Dec 08 11:25:39 CST 2014 - */ - int updateByExample(@Param("record") Country2 record, @Param("example") Country2Example example); } \ No newline at end of file diff --git a/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.xml b/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.xml index 5994fbe..9982a06 100644 --- a/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.xml +++ b/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.xml @@ -11,157 +11,4 @@ - - - - - - - - - - and ${criterion.condition} - - - and ${criterion.condition} #{criterion.value} - - - and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} - - - and ${criterion.condition} - - #{listItem} - - - - - - - - - - - - - - - - - - - and ${criterion.condition} - - - and ${criterion.condition} #{criterion.value} - - - and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} - - - and ${criterion.condition} - - #{listItem} - - - - - - - - - - - - id, countryname, countrycode - - - - - delete from country - - - - - - - - update country - - - id = #{record.id,jdbcType=INTEGER}, - - - countryname = #{record.countryname,jdbcType=VARCHAR}, - - - countrycode = #{record.countrycode,jdbcType=VARCHAR}, - - - - - - - - - update country - set id = #{record.id,jdbcType=INTEGER}, - countryname = #{record.countryname,jdbcType=VARCHAR}, - countrycode = #{record.countrycode,jdbcType=VARCHAR} - - - - \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/jsp/index.jsp b/src/main/webapp/WEB-INF/jsp/index.jsp index 57dc8fb..847ea09 100644 --- a/src/main/webapp/WEB-INF/jsp/index.jsp +++ b/src/main/webapp/WEB-INF/jsp/index.jsp @@ -150,20 +150,7 @@

         ===============================================================================================
-        推荐使用Mybatis分页插件
-        ===============================================================================================
-
-        Mybatis分页插件oschub的项目地址:http://git.oschina.net/free/Mybatis_PageHelper
-
-        Mybatis分页插件github的项目地址:https://github.com/pagehelper/Mybatis-PageHelper
-
-        分页插件文档地址:http://git.oschina.net/free/Mybatis_PageHelper/wikis/home
-
-        Mybatis-Sample(分页插件测试项目):http://git.oschina.net/free/Mybatis-Sample
-
-        Mybatis项目:https://github.com/mybatis/mybatis-3
-
-        Mybatis文档:http://mybatis.github.io/mybatis-3/zh/index.html
+        MyBatis工具:www.mybatis.tk
 
         Mybatis专栏:
         Mybatis示例:http://blog.csdn.net/column/details/mybatis-sample.html
@@ -178,6 +165,7 @@
         作者邮箱: abel533@gmail.com
 
         推荐一个Mybatis的QQ群: 146127540
+        ===============================================================================================
             
From 051d7c62827e30d5876dbdef23d09824ad12e826 Mon Sep 17 00:00:00 2001 From: isea533 Date: Fri, 5 Jun 2015 11:43:44 +0800 Subject: [PATCH 08/10] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=96=87=E6=A1=A3?= =?UTF-8?q?=EF=BC=8C=E5=BC=BA=E8=B0=83spring3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 6d97691..eebd81a 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,19 @@ #SSM集成的基础项目,项目使用Maven管理 +#MyBatis3.2.8 + +#Spring3.2.12 + 项目使用Spring3.2.12+SpringMVC3.2.12+Mybatis3.2.8 项目集成了Mybatis分页插件和通用Mapper插件 项目使用的hsqldb内存数据库,根据需要可以切换为其他支持的数据库 +#Spring4分支 + +本项目还有一个使用Spring4的分支:[Spring4](https://github.com/abel533/Mybatis-Spring/tree/spring4) + ##推荐使用Mybatis通用Mapper 项目地址:https://github.com/abel533/Mapper From 13d305ac5c9146ce875ad21dd8f9222e35985cda Mon Sep 17 00:00:00 2001 From: isea533 Date: Wed, 10 Jun 2015 09:11:34 +0800 Subject: [PATCH 09/10] =?UTF-8?q?=E5=8D=87=E7=BA=A7=E9=80=9A=E7=94=A8Mappe?= =?UTF-8?q?r=E4=B8=BA3.1.0-SNAPSHOT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 15 ++-------- .../mybatis/mapper/Country2Mapper.java | 6 +--- .../isea533/mybatis/mapper/CountryMapper.java | 2 +- .../mybatis/mapper/UserInfoMapper.java | 2 +- .../mybatis/mapper/UserLoginMapper.java | 2 +- src/main/resources/applicationContext.xml | 14 ++++----- .../mybatis/test/PageEntityMapperTest.java | 30 ------------------- 7 files changed, 11 insertions(+), 60 deletions(-) delete mode 100644 src/test/java/com/isea533/mybatis/test/PageEntityMapperTest.java diff --git a/pom.xml b/pom.xml index 8aaeac0..8772d77 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ UTF-8 ${basedir}/src/main/java - 3.0.0 + 3.1.0-SNAPSHOT 3.7.4 @@ -183,21 +183,10 @@ - com.github.abel533 + tk.mybatis mapper ${mapper.version} - - com.github.abel533 - entitymapper - 1.0.0 - - - com.github.abel533 - mapper - - -
diff --git a/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java b/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java index 662f681..4751606 100644 --- a/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java +++ b/src/main/java/com/isea533/mybatis/mapper/Country2Mapper.java @@ -1,11 +1,7 @@ package com.isea533.mybatis.mapper; -import com.github.abel533.mapper.Mapper; import com.isea533.mybatis.model.Country2; -import com.isea533.mybatis.model.Country2Example; -import org.apache.ibatis.annotations.Param; - -import java.util.List; +import tk.mybatis.mapper.common.Mapper; public interface Country2Mapper extends Mapper { diff --git a/src/main/java/com/isea533/mybatis/mapper/CountryMapper.java b/src/main/java/com/isea533/mybatis/mapper/CountryMapper.java index 7f1260e..0b200d7 100644 --- a/src/main/java/com/isea533/mybatis/mapper/CountryMapper.java +++ b/src/main/java/com/isea533/mybatis/mapper/CountryMapper.java @@ -1,6 +1,6 @@ package com.isea533.mybatis.mapper; -import com.github.abel533.mapper.Mapper; +import tk.mybatis.mapper.common.Mapper; import com.isea533.mybatis.model.Country; public interface CountryMapper extends Mapper { diff --git a/src/main/java/com/isea533/mybatis/mapper/UserInfoMapper.java b/src/main/java/com/isea533/mybatis/mapper/UserInfoMapper.java index da5bc0e..fef2a0b 100644 --- a/src/main/java/com/isea533/mybatis/mapper/UserInfoMapper.java +++ b/src/main/java/com/isea533/mybatis/mapper/UserInfoMapper.java @@ -1,6 +1,6 @@ package com.isea533.mybatis.mapper; -import com.github.abel533.mapper.Mapper; +import tk.mybatis.mapper.common.Mapper; import com.isea533.mybatis.model.UserInfo; public interface UserInfoMapper extends Mapper { diff --git a/src/main/java/com/isea533/mybatis/mapper/UserLoginMapper.java b/src/main/java/com/isea533/mybatis/mapper/UserLoginMapper.java index f47623a..cd4a877 100644 --- a/src/main/java/com/isea533/mybatis/mapper/UserLoginMapper.java +++ b/src/main/java/com/isea533/mybatis/mapper/UserLoginMapper.java @@ -1,6 +1,6 @@ package com.isea533.mybatis.mapper; -import com.github.abel533.mapper.Mapper; +import tk.mybatis.mapper.common.Mapper; import com.isea533.mybatis.model.UserLogin; public interface UserLoginMapper extends Mapper { diff --git a/src/main/resources/applicationContext.xml b/src/main/resources/applicationContext.xml index 7301178..f148304 100644 --- a/src/main/resources/applicationContext.xml +++ b/src/main/resources/applicationContext.xml @@ -42,12 +42,12 @@
- + - mappers=com.github.abel533.mapper.Mapper - IDENTITY=MYSQL - notEmpty=true + mappers=tk.mybatis.mapper.common.Mapper + IDENTITY=MYSQL + notEmpty=true @@ -56,11 +56,7 @@ - - - - - + diff --git a/src/test/java/com/isea533/mybatis/test/PageEntityMapperTest.java b/src/test/java/com/isea533/mybatis/test/PageEntityMapperTest.java deleted file mode 100644 index 4d865e1..0000000 --- a/src/test/java/com/isea533/mybatis/test/PageEntityMapperTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.isea533.mybatis.test; - -import com.github.abel533.entity.EntityMapper; -import com.github.abel533.entity.Example; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; -import com.isea533.mybatis.model.Country; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import java.util.List; - -/** - * Created by liuzh on 2015/3/7. - */ -public class PageEntityMapperTest extends BasicTest { - - @Autowired - private EntityMapper entityMapper; - - @Test - public void test(){ - Example example = new Example(Country.class); - example.createCriteria().andGreaterThan("id",100); - PageHelper.startPage(2,10); - List countries = entityMapper.selectByExample(example); - PageInfo pageInfo = new PageInfo(countries); - System.out.println(pageInfo.getTotal()); - } -} From 24bfcefa428258706455ef14841d1bf7c19e0279 Mon Sep 17 00:00:00 2001 From: isea533 Date: Wed, 10 Jun 2015 15:12:52 +0800 Subject: [PATCH 10/10] =?UTF-8?q?=E9=80=9A=E7=94=A8Mapper=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E5=8D=87=E7=BA=A7=E4=B8=BA3.1.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 8772d77..62025d4 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ UTF-8 ${basedir}/src/main/java - 3.1.0-SNAPSHOT + 3.1.0 3.7.4