├── src └── main │ ├── java │ └── com │ │ └── github │ │ └── yt │ │ ├── mybatis │ │ ├── annotations │ │ │ └── BaseResult.java │ │ ├── config │ │ │ ├── page │ │ │ │ ├── PageConvert.java │ │ │ │ ├── CommonPageService.java │ │ │ │ └── PageConfiguration.java │ │ │ └── fields │ │ │ │ ├── DefaultFieldsDefault.java │ │ │ │ ├── FieldsDefault.java │ │ │ │ └── FieldsConfiguration.java │ │ ├── utils │ │ │ ├── ChainMap.java │ │ │ ├── PropertyConfigurer.java │ │ │ ├── BeanUtils.java │ │ │ ├── SpringContextUtils.java │ │ │ ├── DateTimeFormatter.java │ │ │ └── JPAUtils.java │ │ ├── result │ │ │ └── QueryResult.java │ │ ├── dao │ │ │ ├── MapperProvider.java │ │ │ ├── provider │ │ │ │ ├── RemoveProvider.java │ │ │ │ ├── ModifyProvider.java │ │ │ │ ├── SaveProvider.java │ │ │ │ └── SearchProvider.java │ │ │ └── BaseMapper.java │ │ ├── handler │ │ │ ├── SQLJoinHandler.java │ │ │ └── QueryHandler.java │ │ ├── service │ │ │ ├── BaseService.java │ │ │ └── impl │ │ │ │ └── ServiceSupport.java │ │ ├── mybatis │ │ │ ├── SqlBuilder.java │ │ │ └── SQL.java │ │ └── domain │ │ │ └── BaseEntity.java │ │ ├── web │ │ ├── utils │ │ │ └── WebUtils.java │ │ ├── result │ │ │ ├── HttpResultEntity.java │ │ │ └── HttpResultHandler.java │ │ └── controller │ │ │ └── BaseController.java │ │ └── generator │ │ ├── ColumnData.java │ │ ├── CommonPageParser.java │ │ ├── CreateBean.java │ │ └── JavaCodeGenerator.java │ └── resources │ ├── Service.java.vm │ ├── Mapper.java.vm │ ├── Bean.java.vm │ ├── Mapper.xml.vm │ ├── ServiceImpl.java.vm │ └── Controller.java.vm ├── pom.xml └── README.md /src/main/java/com/github/yt/mybatis/annotations/BaseResult.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.annotations; 2 | 3 | 4 | public interface BaseResult { 5 | 6 | BaseResult getBaseResult(); 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/main/resources/Service.java.vm: -------------------------------------------------------------------------------- 1 | package ${modulePackage}.service; 2 | 3 | import com.github.yt.mybatis.service.BaseService; 4 | import ${modulePackage}.domain.${className}; 5 | 6 | /** 7 | * ${codeName}服务层 8 | * 9 | */ 10 | public interface ${replaceSuffixClassName}Service extends BaseService<${className}> { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/resources/Mapper.java.vm: -------------------------------------------------------------------------------- 1 | package ${modulePackage}.dao; 2 | 3 | import ${modulePackage}.domain.${className}; 4 | import com.github.yt.mybatis.dao.BaseMapper; 5 | 6 | /** 7 | * ${replaceSuffixClassName} Mapper 8 | * 9 | */ 10 | public interface ${replaceSuffixClassName}Mapper extends BaseMapper<${className}> { 11 | 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/config/page/PageConvert.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.config.page; 2 | 3 | 4 | import com.github.yt.mybatis.handler.QueryHandler; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | 9 | public interface PageConvert { 10 | 11 | void convert(QueryHandler queryHandler, HttpServletRequest request); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/resources/Bean.java.vm: -------------------------------------------------------------------------------- 1 | package ${modulePackage}.domain; 2 | 3 | import com.github.yt.mybatis.domain.BaseEntity; 4 | import org.hibernate.validator.constraints.NotEmpty; 5 | import org.hibernate.validator.constraints.Length; 6 | 7 | 8 | ##@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL) 9 | @javax.persistence.Table(name = "${tableName}") 10 | public class ${className} extends BaseEntity<${className}>{ 11 | ${feilds} 12 | } 13 | -------------------------------------------------------------------------------- /src/main/resources/Mapper.xml.vm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | #foreach($item in $!{columnDatas}) 7 | 8 | #end 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/config/fields/DefaultFieldsDefault.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.config.fields; 2 | 3 | 4 | public class DefaultFieldsDefault implements FieldsDefault { 5 | 6 | 7 | @Override 8 | public String getOperator() { 9 | return "default"; 10 | } 11 | 12 | @Override 13 | public String getOperatorId() { 14 | return ""; 15 | } 16 | 17 | @Override 18 | public String getModifyOperator() { 19 | return "default"; 20 | } 21 | 22 | @Override 23 | public String getModifyOperatorId() { 24 | return ""; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/config/fields/FieldsDefault.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.config.fields; 2 | 3 | /** 4 | * domain默认值注入接口 5 | */ 6 | public interface FieldsDefault { 7 | 8 | /** 9 | * 获取操作人 10 | * 11 | * @return 操作人 12 | */ 13 | String getOperator(); 14 | 15 | /** 16 | * 获取操作人id 17 | * 18 | * @return 操作人id 19 | */ 20 | String getOperatorId(); 21 | 22 | /** 23 | * 获取修改人 24 | * 25 | * @return 修改人 26 | */ 27 | String getModifyOperator(); 28 | 29 | /** 30 | * 获取修改人id 31 | * 32 | * @return 修改人id 33 | */ 34 | String getModifyOperatorId(); 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/utils/ChainMap.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.utils; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | 7 | public class ChainMap extends LinkedHashMap { 8 | 9 | private static final long serialVersionUID = -8256232046919043447L; 10 | 11 | /** 12 | * 链表式赋值,返回值为map对象本身 13 | * 14 | * @param key 键 15 | * @param value 值 16 | * @return 返回map本身 17 | */ 18 | public ChainMap chainPut(K key, V value) { 19 | super.put(key, value); 20 | return this; 21 | } 22 | 23 | public ChainMap chainPutAll(Map map){ 24 | if(map!=null) { 25 | super.putAll(map); 26 | } 27 | return this; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/web/utils/WebUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.web.utils; 2 | 3 | 4 | import javax.servlet.http.HttpServletRequest; 5 | 6 | public class WebUtils extends org.springframework.web.util.WebUtils { 7 | 8 | /** 9 | * 获取url和request参数 10 | */ 11 | public static String getParameterValues(HttpServletRequest request) { 12 | Object pathVariables = request.getAttribute("org.springframework.web.servlet.View.pathVariables"); 13 | String parameterValues = org.springframework.web.util.WebUtils.getParametersStartingWith(request, null).toString(); 14 | if (pathVariables == null) { 15 | pathVariables = "{}"; 16 | } 17 | return "parameterValues:" + parameterValues + ",pathVariables:" + pathVariables; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/config/page/CommonPageService.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.config.page; 2 | 3 | 4 | import com.github.yt.mybatis.handler.QueryHandler; 5 | import org.apache.commons.lang3.StringUtils; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | 9 | 10 | public class CommonPageService implements PageConvert { 11 | 12 | @Override 13 | public void convert(QueryHandler queryHandler, HttpServletRequest request) { 14 | String pageSize = request.getParameter("pageSize"); 15 | String currentPage = request.getParameter("currentPage"); 16 | Integer pageSize1 = StringUtils.isEmpty(pageSize) ? 10 : Integer.valueOf(pageSize); 17 | Integer currentPage1 = StringUtils.isEmpty(currentPage) ? 1 : Integer.valueOf(currentPage); 18 | queryHandler.setStart((currentPage1 - 1) * pageSize1); 19 | queryHandler.setLimit(pageSize1); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/resources/ServiceImpl.java.vm: -------------------------------------------------------------------------------- 1 | package ${modulePackage}.service.impl; 2 | 3 | import com.github.yt.mybatis.service.impl.ServiceSupport; 4 | import ${modulePackage}.dao.${replaceSuffixClassName}Mapper; 5 | import ${modulePackage}.domain.${className}; 6 | import ${modulePackage}.service.${replaceSuffixClassName}Service; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Service; 10 | 11 | @Service("${replaceSuffixLowerName}Service") 12 | public class ${replaceSuffixClassName}ServiceImpl extends ServiceSupport<${className}, ${replaceSuffixClassName}Mapper> implements ${replaceSuffixClassName}Service { 13 | 14 | @Autowired 15 | private ${replaceSuffixClassName}Mapper ${replaceSuffixLowerName}Mapper; 16 | 17 | @Override 18 | public ${replaceSuffixClassName}Mapper getMapper() { 19 | return ${replaceSuffixLowerName}Mapper; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/config/page/PageConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.config.page; 2 | 3 | 4 | import com.github.yt.mybatis.utils.SpringContextUtils; 5 | import org.springframework.beans.factory.NoSuchBeanDefinitionException; 6 | 7 | public class PageConfiguration { 8 | 9 | private static PageConvert pageConvert; 10 | 11 | public static PageConvert create() { 12 | if (pageConvert != null) { 13 | return pageConvert; 14 | } 15 | Object object = null; 16 | boolean error = false; 17 | try { 18 | object = SpringContextUtils.getBean("ytPageConfig"); 19 | } catch (NoSuchBeanDefinitionException e) { 20 | error = true; 21 | } 22 | if (error || object == null) { 23 | pageConvert = new CommonPageService(); 24 | } else { 25 | pageConvert = (PageConvert) object; 26 | } 27 | return pageConvert; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/config/fields/FieldsConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.config.fields; 2 | 3 | 4 | import com.github.yt.mybatis.utils.SpringContextUtils; 5 | import org.springframework.beans.factory.NoSuchBeanDefinitionException; 6 | 7 | public class FieldsConfiguration { 8 | 9 | private static FieldsDefault fieldsDefault; 10 | 11 | public static FieldsDefault create() { 12 | if (fieldsDefault != null) { 13 | return fieldsDefault; 14 | } 15 | Object object = null; 16 | boolean error = false; 17 | try { 18 | object = SpringContextUtils.getBean("ytFieldsConfig"); 19 | } catch (NoSuchBeanDefinitionException e) { 20 | error = true; 21 | } 22 | if (error || object == null) { 23 | fieldsDefault = new DefaultFieldsDefault(); 24 | } else { 25 | fieldsDefault = (FieldsDefault) object; 26 | } 27 | return fieldsDefault; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/utils/PropertyConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.utils; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; 5 | import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | import java.util.Properties; 10 | 11 | 12 | public class PropertyConfigurer extends PropertyPlaceholderConfigurer { 13 | private static Map propertiesMap = new HashMap<>(); 14 | 15 | @Override 16 | protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { 17 | super.processProperties(beanFactoryToProcess, props); 18 | 19 | for (Object key : props.keySet()) { 20 | propertiesMap.put(key.toString(), props.get(key).toString()); 21 | } 22 | } 23 | 24 | public static String getProperty(String key) { 25 | return propertiesMap.get(key); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/result/QueryResult.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.result; 2 | 3 | import com.fasterxml.jackson.annotation.JsonView; 4 | import com.github.yt.mybatis.annotations.BaseResult; 5 | 6 | import java.util.List; 7 | 8 | 9 | public class QueryResult { 10 | 11 | /** 12 | * 结果集 13 | */ 14 | private List data; 15 | 16 | /** 17 | * 总数 18 | */ 19 | private long recordsTotal; 20 | 21 | public QueryResult() { 22 | } 23 | 24 | public QueryResult(List data) { 25 | this.data = data; 26 | if(null!=data){ 27 | this.recordsTotal = data.size(); 28 | } 29 | } 30 | 31 | @JsonView(BaseResult.class) 32 | public List getData() { 33 | return data; 34 | } 35 | 36 | public QueryResult setData(List data) { 37 | this.data = data; 38 | return this; 39 | } 40 | 41 | @JsonView(BaseResult.class) 42 | public long getRecordsTotal() { 43 | return recordsTotal; 44 | } 45 | 46 | public QueryResult setRecordsTotal(long recordsTotal) { 47 | this.recordsTotal = recordsTotal; 48 | return this; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/web/result/HttpResultEntity.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.web.result; 2 | 3 | public class HttpResultEntity { 4 | 5 | private String errorCode; 6 | 7 | private String message; 8 | 9 | private Object result; 10 | 11 | public HttpResultEntity() { 12 | } 13 | 14 | public HttpResultEntity(String errorCode, String message) { 15 | this.errorCode = errorCode; 16 | this.message = message; 17 | } 18 | 19 | public HttpResultEntity(String errorCode, String message, Object result) { 20 | this.errorCode = errorCode; 21 | this.message = message; 22 | this.result = result; 23 | } 24 | 25 | public String getErrorCode() { 26 | return errorCode; 27 | } 28 | 29 | public void setErrorCode(String errorCode) { 30 | this.errorCode = errorCode; 31 | } 32 | 33 | public String getMessage() { 34 | return message; 35 | } 36 | 37 | public void setMessage(String message) { 38 | this.message = message; 39 | } 40 | 41 | public Object getResult() { 42 | return result; 43 | } 44 | 45 | public void setResult(Object result) { 46 | this.result = result; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/dao/MapperProvider.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.dao; 2 | 3 | 4 | import com.github.yt.base.exception.BaseErrorException; 5 | import org.apache.commons.lang3.StringUtils; 6 | 7 | import javax.persistence.Table; 8 | import java.lang.annotation.Annotation; 9 | 10 | import static com.github.yt.mybatis.mybatis.SqlBuilder.BEGIN; 11 | import static com.github.yt.mybatis.mybatis.SqlBuilder.SQL; 12 | 13 | 14 | public class MapperProvider { 15 | 16 | protected void begin() { 17 | BEGIN(); 18 | } 19 | 20 | protected String sql() { 21 | return SQL(); 22 | } 23 | 24 | protected String getTableName(Class entityClass) { 25 | Annotation table = entityClass.getAnnotation(Table.class); 26 | if (null == table) { 27 | throw new BaseErrorException(StringUtils.join("实体未配置Table注解 entityClass =", entityClass.getName())); 28 | } 29 | String tableName = ((Table) table).name(); 30 | if (StringUtils.isEmpty(tableName)) { 31 | throw new BaseErrorException(StringUtils.join("实体的Table注解未配置name属性 entityClass =", entityClass.getName())); 32 | } 33 | return tableName; 34 | } 35 | 36 | protected String getTableNameWithAlias(Class entityClass) { 37 | return StringUtils.join(getTableName(entityClass), " t"); 38 | } 39 | 40 | protected String getEqualsValue(String column, String value) { 41 | return StringUtils.join(column, " = #{", value, "}"); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/web/result/HttpResultHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.web.result; 2 | 3 | public class HttpResultHandler { 4 | 5 | public static HttpResultEntity getSuccessResult() { 6 | return getSuccessResult((Object)null); 7 | } 8 | 9 | public static HttpResultEntity getSuccessResult(Object result) { 10 | return new HttpResultEntity(HttpResultHandler.HttpResultEnum.SUCCESS.errorCode, HttpResultHandler.HttpResultEnum.SUCCESS.name(), result); 11 | } 12 | 13 | public static HttpResultEntity getErrorResult() { 14 | return new HttpResultEntity(HttpResultHandler.HttpResultEnum.ERROR.errorCode, HttpResultHandler.HttpResultEnum.ERROR.name()); 15 | } 16 | 17 | public static HttpResultEntity getErrorResult(Object result) { 18 | return new HttpResultEntity(HttpResultHandler.HttpResultEnum.ERROR.errorCode, HttpResultHandler.HttpResultEnum.ERROR.name(), result); 19 | } 20 | 21 | public static HttpResultEntity getErrorResult(String message) { 22 | return new HttpResultEntity(HttpResultEnum.ERROR.errorCode, message); 23 | } 24 | 25 | public static HttpResultEntity getErrorResult(String errorCode, String message) { 26 | return new HttpResultEntity(errorCode, message); 27 | } 28 | 29 | enum HttpResultEnum { 30 | ERROR("0"), 31 | SUCCESS("1"); 32 | private String errorCode; 33 | HttpResultEnum(String errorCode) { 34 | this.errorCode = errorCode; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/utils/BeanUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.utils; 2 | 3 | 4 | import com.github.yt.base.exception.BaseErrorException; 5 | import org.apache.commons.lang3.StringUtils; 6 | 7 | import java.lang.reflect.Field; 8 | 9 | 10 | public class BeanUtils { 11 | 12 | /** 13 | * 将所有对象的属性及值都放到map中 14 | * 15 | * @param objs 实体列表 16 | * @return 实体转map 17 | */ 18 | public static ChainMap getValueMap(Object... objs) { 19 | try { 20 | ChainMap map = new ChainMap<>(); 21 | for (Object obj : objs) { 22 | if (null == obj) { 23 | continue; 24 | } 25 | for (Class c = obj.getClass(); Object.class != c; c = c.getSuperclass()) { 26 | for (Field field : c.getDeclaredFields()) { 27 | field.setAccessible(true); 28 | Object value = field.get(obj); 29 | if (null == value) { 30 | continue; 31 | } 32 | if (field.getType().isAssignableFrom(String.class) && StringUtils.isEmpty((String) value)) { 33 | continue; 34 | } 35 | map.put(field.getName(), value); 36 | } 37 | } 38 | } 39 | return map; 40 | } catch (Exception e) { 41 | throw new BaseErrorException("Object to Map convert Error", e); 42 | } 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/handler/SQLJoinHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.handler; 2 | 3 | 4 | public class SQLJoinHandler { 5 | public static enum JoinType { 6 | JOIN, INNER_JOIN, LEFT_OUTER_JOIN, RIGHT_OUTER_JOIN, OUTER_JOIN 7 | } 8 | 9 | /** 10 | * 查询的列 11 | */ 12 | private String selectColumns; 13 | /** 14 | * 链接类型 15 | */ 16 | private JoinType joinType; 17 | /** 18 | * join sql 19 | */ 20 | private String joinSql; 21 | 22 | public SQLJoinHandler() { 23 | } 24 | 25 | public SQLJoinHandler(String selectColumns, JoinType joinType, String joinSql) { 26 | this.selectColumns = selectColumns; 27 | this.joinType = joinType; 28 | this.joinSql = joinSql; 29 | } 30 | 31 | public SQLJoinHandler(JoinType joinType, String joinSql) { 32 | this.joinType = joinType; 33 | this.joinSql = joinSql; 34 | } 35 | 36 | public String getSelectColumns() { 37 | return selectColumns; 38 | } 39 | 40 | public SQLJoinHandler setSelectColumns(String selectColumns) { 41 | this.selectColumns = selectColumns; 42 | return this; 43 | } 44 | 45 | public JoinType getJoinType() { 46 | return joinType; 47 | } 48 | 49 | public SQLJoinHandler setJoinType(JoinType joinType) { 50 | this.joinType = joinType; 51 | return this; 52 | } 53 | 54 | public String getJoinSql() { 55 | return joinSql; 56 | } 57 | 58 | public SQLJoinHandler setJoinSql(String joinSql) { 59 | this.joinSql = joinSql; 60 | return this; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/utils/SpringContextUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.utils; 2 | 3 | import org.springframework.context.ApplicationContext; 4 | import org.springframework.context.ApplicationContextAware; 5 | import org.springframework.stereotype.Component; 6 | import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext; 7 | 8 | import java.util.Map; 9 | 10 | @Component 11 | public class SpringContextUtils implements ApplicationContextAware { 12 | 13 | private static ApplicationContext applicationContext; 14 | 15 | public SpringContextUtils() { 16 | } 17 | 18 | public void setApplicationContext(ApplicationContext _applicationContext) { 19 | applicationContext = _applicationContext; 20 | } 21 | 22 | public static void refresh() { 23 | ((AbstractRefreshableWebApplicationContext) applicationContext).refresh(); 24 | } 25 | 26 | public static ApplicationContext getApplicationContext() { 27 | return applicationContext; 28 | } 29 | 30 | public static Map getBeans(Class type) { 31 | return applicationContext.getBeansOfType(type); 32 | } 33 | 34 | public static Object getBean(String beanName) { 35 | return applicationContext.getBean(beanName); 36 | } 37 | 38 | 39 | public static T getBean(Class beanClass) { 40 | return applicationContext.getBean(beanClass); 41 | } 42 | 43 | public static Boolean containsBean(String beanName) { 44 | return applicationContext.containsBean(beanName); 45 | } 46 | 47 | public static String getProperty(String key) { 48 | return PropertyConfigurer.getProperty(key); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/dao/provider/RemoveProvider.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.dao.provider; 2 | 3 | 4 | import com.github.yt.mybatis.dao.BaseMapper; 5 | import com.github.yt.mybatis.dao.MapperProvider; 6 | import com.github.yt.mybatis.domain.BaseEntity; 7 | import com.github.yt.base.exception.BaseErrorException; 8 | import com.github.yt.mybatis.utils.JPAUtils; 9 | import org.apache.commons.lang3.StringUtils; 10 | 11 | import java.util.Map; 12 | 13 | import static com.github.yt.mybatis.mybatis.SqlBuilder.*; 14 | 15 | 16 | public class RemoveProvider extends MapperProvider { 17 | 18 | public String delete(Map param) { 19 | begin(); 20 | Class entityClass = (Class) param.get(BaseMapper.ENTITY_CLASS); 21 | if (param.get(BaseMapper.ID) == null || StringUtils.isEmpty(param.get(BaseMapper.ID).toString())) { 22 | throw new BaseErrorException(StringUtils.join(entityClass.getName(), ",删除时主键不能为空!")); 23 | } 24 | DELETE_FROM(getTableName(entityClass)); 25 | WHERE(getEqualsValue(JPAUtils.getAnnotationColumnName(JPAUtils.getIdField(entityClass)), BaseMapper.ID)); 26 | return sql(); 27 | } 28 | 29 | public String logicDelete(Map param) { 30 | begin(); 31 | Class entityClass = (Class) param.get(BaseMapper.ENTITY_CLASS); 32 | if (param.get(BaseMapper.ID) == null || StringUtils.isEmpty(param.get(BaseMapper.ID).toString())) { 33 | throw new BaseErrorException(StringUtils.join(entityClass.getName(), ",删除时主键不能为空!")); 34 | } 35 | UPDATE(getTableName(entityClass)); 36 | SET(BaseEntity.DELETE_FLAG + "=1"); 37 | WHERE(getEqualsValue(JPAUtils.getAnnotationColumnName(JPAUtils.getIdField(entityClass)), BaseMapper.ID)); 38 | return sql(); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/generator/ColumnData.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.generator; 2 | 3 | 4 | public class ColumnData { 5 | 6 | private String columnName; 7 | private String dataType; 8 | private String columnComment; 9 | private String columnNameContainEntity; 10 | private Boolean isPriKey; 11 | private Long columnLength; 12 | private Boolean isNullable; 13 | private String columnDefault; 14 | 15 | public Boolean getIsPriKey() { 16 | return isPriKey; 17 | } 18 | 19 | public void setIsPriKey(Boolean isPriKey) { 20 | this.isPriKey = isPriKey; 21 | } 22 | 23 | public String getColumnName() { 24 | return columnName; 25 | } 26 | 27 | public void setColumnName(String columnName) { 28 | this.columnName = columnName; 29 | } 30 | 31 | public String getDataType() { 32 | return dataType; 33 | } 34 | 35 | public void setDataType(String dataType) { 36 | this.dataType = dataType; 37 | } 38 | 39 | public String getColumnComment() { 40 | return columnComment; 41 | } 42 | 43 | public void setColumnComment(String columnComment) { 44 | this.columnComment = columnComment; 45 | } 46 | 47 | public String getColumnNameContainEntity() { 48 | return columnNameContainEntity; 49 | } 50 | 51 | public void setColumnNameContainEntity(String columnNameContainEntity) { 52 | this.columnNameContainEntity = columnNameContainEntity; 53 | } 54 | 55 | public Long getColumnLength() { 56 | return columnLength; 57 | } 58 | 59 | public void setColumnLength(Long columnLength) { 60 | this.columnLength = columnLength; 61 | } 62 | 63 | public Boolean getIsNullable() { 64 | return isNullable; 65 | } 66 | 67 | public void setIsNullable(Boolean isNullable) { 68 | this.isNullable = isNullable; 69 | } 70 | 71 | public String getColumnDefault() { 72 | return columnDefault; 73 | } 74 | 75 | public void setColumnDefault(String columnDefault) { 76 | this.columnDefault = columnDefault; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/web/controller/BaseController.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.web.controller; 2 | 3 | 4 | import com.github.yt.base.exception.BaseAccidentException; 5 | import com.github.yt.web.result.HttpResultEntity; 6 | import com.github.yt.web.result.HttpResultHandler; 7 | import com.github.yt.web.utils.WebUtils; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.web.bind.annotation.ExceptionHandler; 11 | 12 | import javax.annotation.Resource; 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import javax.servlet.http.HttpSession; 16 | 17 | public class BaseController { 18 | 19 | private static Logger logger = LoggerFactory.getLogger(BaseController.class); 20 | 21 | @Resource 22 | protected HttpServletRequest request; 23 | 24 | @Resource 25 | protected HttpServletResponse response; 26 | 27 | @Resource 28 | protected HttpSession session; 29 | 30 | @ExceptionHandler 31 | public HttpResultEntity exceptionHandler(HttpServletRequest request, Exception ex) { 32 | 33 | String logTemplate = "\n url:★{}★\n parameterValues : ★{}★"; 34 | String parameterValues = WebUtils.getParameterValues(request); 35 | String serverName = request.getServerName(); 36 | String operatorLogStr = "\n ★{User-Agent:[" + request.getHeader("User-Agent") + "],serverName:[" + serverName + "]"; 37 | 38 | if (ex instanceof BaseAccidentException) { 39 | if (((BaseAccidentException) ex).getLogFlag()) { 40 | logger.error(operatorLogStr + ex.getMessage() + logTemplate, request.getServletPath(), 41 | parameterValues, ex); 42 | } else { 43 | logger.warn(operatorLogStr + ex.getMessage() + logTemplate, request.getServletPath(), 44 | parameterValues, ex); 45 | } 46 | return HttpResultHandler.getErrorResult(((BaseAccidentException) ex).getErrorCode(), ex.getMessage()); 47 | } 48 | 49 | logger.error(operatorLogStr + "uncaught exception," + logTemplate, request.getServletPath(), 50 | parameterValues, ex); 51 | return HttpResultHandler.getErrorResult(); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/service/BaseService.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.service; 2 | 3 | import com.github.yt.mybatis.handler.QueryHandler; 4 | import com.github.yt.mybatis.result.QueryResult; 5 | 6 | import java.io.Serializable; 7 | import java.util.List; 8 | 9 | /** 10 | * 服务接口的基类 11 | * 12 | * @param 此服务接口服务的数据模型,即model 13 | */ 14 | public interface BaseService { 15 | 16 | /** 17 | * 保存实体 18 | * 19 | * @param entity 待保存的实体 20 | */ 21 | void save(T entity); 22 | 23 | /** 24 | * 批量保存 25 | * 26 | * @param entities 待保存实体列表 27 | */ 28 | void saveBatch(List entities); 29 | 30 | /** 31 | * 只保存非空字段 32 | * 33 | * @param entity 待保存的实体 34 | */ 35 | void saveForSelective(T entity); 36 | 37 | /** 38 | * 更新实体 39 | * 40 | * @param entity 业务实体 41 | */ 42 | void update(T entity); 43 | 44 | /** 45 | * 只更新非空字段 46 | * 47 | * @param entity 业务实体 48 | */ 49 | void updateForSelective(T entity); 50 | 51 | /** 52 | * 删除实体 53 | * 54 | * @param clazz clazz 55 | * @param id 业务实体ID 56 | */ 57 | void delete(Class clazz, Serializable id); 58 | 59 | /** 60 | * 逻辑删除实体 61 | * 62 | * @param clazz clazz 63 | * @param id 业务实体ID 64 | */ 65 | void logicDelete(Class clazz, Serializable id); 66 | 67 | /** 68 | * 根据ID获取实体 69 | * 70 | * @param id 业务实体ID 71 | * @return 业务实体 72 | */ 73 | T find(Class clazz, Serializable id); 74 | 75 | /** 76 | * 按条件查询记录集合 77 | * 78 | * @param entity 业务实体类或业务查询实体类 79 | * @return 业务实体集合 80 | */ 81 | List findAll(T entity); 82 | 83 | /** 84 | * 按条件查询记录集合 85 | * 86 | * @param entity 业务实体类或业务查询实体类 87 | * @param queryHandler 查询辅助类 88 | * @return 业务实体集合 89 | */ 90 | List findAll(T entity, QueryHandler queryHandler); 91 | 92 | /** 93 | * 获取数据 94 | * 95 | * @param entity 查询业务实体 96 | * @param queryHandler 查询辅助类 97 | * @return 根据查询条件查询的查询结果集 98 | */ 99 | QueryResult getData(T entity, QueryHandler queryHandler); 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/mybatis/SqlBuilder.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.mybatis; 2 | 3 | 4 | 5 | public class SqlBuilder { 6 | 7 | private static final ThreadLocal localSQL = new ThreadLocal(); 8 | 9 | static { 10 | BEGIN(); 11 | } 12 | 13 | public static void BEGIN() { 14 | RESET(); 15 | } 16 | 17 | public static void RESET() { 18 | localSQL.set(new SQL()); 19 | } 20 | 21 | public static void UPDATE(String table) { 22 | sql().UPDATE(table); 23 | } 24 | 25 | public static void SET(String sets) { 26 | sql().SET(sets); 27 | } 28 | 29 | public static String SQL() { 30 | try { 31 | return sql().toString(); 32 | } finally { 33 | RESET(); 34 | } 35 | } 36 | 37 | public static void INSERT_INTO(String tableName) { 38 | sql().INSERT_INTO(tableName); 39 | } 40 | 41 | public static void BATCH_SEGMENTATION() { 42 | sql().BATCH_SEGMENTATION(); 43 | } 44 | 45 | public static void BATCH_INSERT_INTO(String tableName) { 46 | sql().BATCH_INSERT_INTO(tableName); 47 | } 48 | 49 | public static void VALUES(String columns, String values) { 50 | sql().VALUES(columns, values); 51 | } 52 | 53 | public static void BATCH_VALUES(String columns, String values) { 54 | sql().BATCH_VALUES(columns, values); 55 | } 56 | 57 | public static void SELECT(String columns) { 58 | sql().SELECT(columns); 59 | } 60 | 61 | public static void SELECT_DISTINCT(String columns) { 62 | sql().SELECT_DISTINCT(columns); 63 | } 64 | 65 | public static void DELETE_FROM(String table) { 66 | sql().DELETE_FROM(table); 67 | } 68 | 69 | public static void FROM(String table) { 70 | sql().FROM(table); 71 | } 72 | 73 | public static void JOIN(String join) { 74 | sql().JOIN(join); 75 | } 76 | 77 | public static void INNER_JOIN(String join) { 78 | sql().INNER_JOIN(join); 79 | } 80 | 81 | public static void LEFT_OUTER_JOIN(String join) { 82 | sql().LEFT_OUTER_JOIN(join); 83 | } 84 | 85 | public static void RIGHT_OUTER_JOIN(String join) { 86 | sql().RIGHT_OUTER_JOIN(join); 87 | } 88 | 89 | public static void OUTER_JOIN(String join) { 90 | sql().OUTER_JOIN(join); 91 | } 92 | 93 | public static void WHERE(String conditions) { 94 | sql().WHERE(conditions); 95 | } 96 | 97 | public static void OR() { 98 | sql().OR(); 99 | } 100 | 101 | public static void AND() { 102 | sql().AND(); 103 | } 104 | 105 | public static void GROUP_BY(String columns) { 106 | sql().GROUP_BY(columns); 107 | } 108 | 109 | public static void HAVING(String conditions) { 110 | sql().HAVING(conditions); 111 | } 112 | 113 | public static void ORDER_BY(String columns) { 114 | sql().ORDER_BY(columns); 115 | } 116 | 117 | private static SQL sql() { 118 | return localSQL.get(); 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/dao/provider/ModifyProvider.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.dao.provider; 2 | 3 | 4 | import com.github.yt.mybatis.dao.BaseMapper; 5 | import com.github.yt.mybatis.dao.MapperProvider; 6 | import com.github.yt.base.exception.BaseErrorException; 7 | import com.github.yt.mybatis.utils.JPAUtils; 8 | import org.apache.commons.lang3.StringUtils; 9 | 10 | import javax.persistence.Column; 11 | import javax.persistence.Id; 12 | import javax.persistence.Table; 13 | import java.lang.annotation.Annotation; 14 | import java.lang.reflect.Field; 15 | import java.util.Collection; 16 | import java.util.Map; 17 | 18 | import static com.github.yt.mybatis.mybatis.SqlBuilder.*; 19 | 20 | 21 | public class ModifyProvider extends MapperProvider { 22 | 23 | public String update(Map param) { 24 | Class entityClass = param.get(BaseMapper.ENTITY).getClass(); 25 | begin(); 26 | UPDATE(getTableName(entityClass)); 27 | Field idField = null; 28 | for (Field field : JPAUtils.getAllFields(entityClass)) { 29 | field.setAccessible(true); 30 | if (field.getType().isAssignableFrom(Collection.class) || null != field.getType().getAnnotation(Table.class)) { 31 | continue; 32 | } 33 | String fieldName = JPAUtils.getAnnotationColumnName(field); 34 | if (null == field.getAnnotation(Id.class)) { 35 | SET(StringUtils.join(getEqualsValue(fieldName, StringUtils.join(BaseMapper.ENTITY, ".", field.getName())))); 36 | continue; 37 | } 38 | idField = field; 39 | WHERE(getEqualsValue(fieldName, StringUtils.join(BaseMapper.ENTITY, ".", field.getName()))); 40 | } 41 | if (null == idField) { 42 | throw new BaseErrorException(StringUtils.join(entityClass.getName(), "实体未配置@Id ")); 43 | } 44 | return sql(); 45 | } 46 | 47 | public String updateForSelective(Map param) { 48 | Class entityClass = param.get(BaseMapper.ENTITY).getClass(); 49 | begin(); 50 | UPDATE(getTableName(entityClass)); 51 | Field idField = null; 52 | for (Field field : JPAUtils.getAllFields(entityClass)) { 53 | field.setAccessible(true); 54 | if (field.getType().isAssignableFrom(Collection.class) || null != field.getType().getAnnotation(Table.class)) { 55 | continue; 56 | } 57 | if (null != field.getAnnotation(Id.class)) { 58 | idField = field; 59 | continue; 60 | } 61 | Object value = JPAUtils.getValue(param.get(BaseMapper.ENTITY), field.getName()); 62 | if (null == value) { 63 | continue; 64 | } 65 | SET(StringUtils.join(getEqualsValue(JPAUtils.getAnnotationColumnName(field), StringUtils.join(BaseMapper.ENTITY, ".", field.getName())))); 66 | } 67 | if (null == idField) { 68 | throw new BaseErrorException(StringUtils.join(entityClass.getName(), "实体未配置@Id ")); 69 | } 70 | WHERE(getEqualsValue(JPAUtils.getAnnotationColumnName(idField), StringUtils.join(BaseMapper.ENTITY, ".", idField.getName()))); 71 | return sql(); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/domain/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.domain; 2 | 3 | import com.alibaba.fastjson.annotation.JSONField; 4 | import com.fasterxml.jackson.annotation.JsonFormat; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Table; 8 | import javax.persistence.Transient; 9 | import java.io.Serializable; 10 | import java.util.Date; 11 | 12 | @Table 13 | public class BaseEntity> implements Serializable { 14 | 15 | private static final long serialVersionUID = 6468926052770326495L; 16 | 17 | @Transient 18 | public static final String DEFAULT_OPERATOR = "default"; 19 | @Transient 20 | public static final String OPERATOR_ID = "operatorId"; 21 | @Transient 22 | public static final String OPERATOR_NAME = "operatorName"; 23 | @Transient 24 | public static final String DELETE_FLAG = "deleteFlag"; 25 | 26 | // 创建时间 27 | private Date createDateTime; 28 | // 修改时间 29 | private Date modifyDateTime; 30 | // 创建人ID 31 | private String founderId; 32 | // 创建人姓名 33 | private String founderName; 34 | // 修改人ID 35 | private String modifierId; 36 | // 修改人姓名 37 | private String modifierName; 38 | // 删除标示 39 | @Column(nullable = false) 40 | private Boolean deleteFlag; 41 | 42 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") 43 | @JSONField(format= "yyyy-MM-dd HH:mm:ss") 44 | public Date getModifyDateTime() { 45 | return modifyDateTime; 46 | } 47 | 48 | public T setModifyDateTime(Date modifyDateTime) { 49 | this.modifyDateTime = modifyDateTime; 50 | return (T) this; 51 | } 52 | 53 | @JSONField(format= "yyyy-MM-dd HH:mm:ss") 54 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") 55 | public Date getCreateDateTime() { 56 | return createDateTime; 57 | } 58 | 59 | public T setCreateDateTime(Date createDateTime) { 60 | this.createDateTime = createDateTime; 61 | return (T) this; 62 | } 63 | 64 | public String getFounderId() { 65 | return founderId; 66 | } 67 | 68 | public T setFounderId(String founderId) { 69 | this.founderId = founderId; 70 | return (T) this; 71 | } 72 | 73 | public String getFounderName() { 74 | return founderName; 75 | } 76 | 77 | public T setFounderName(String founderName) { 78 | this.founderName = founderName; 79 | return (T) this; 80 | } 81 | 82 | public String getModifierId() { 83 | return modifierId; 84 | } 85 | 86 | public T setModifierId(String modifierId) { 87 | this.modifierId = modifierId; 88 | return (T) this; 89 | } 90 | 91 | public String getModifierName() { 92 | return modifierName; 93 | } 94 | 95 | public T setModifierName(String modifierName) { 96 | this.modifierName = modifierName; 97 | return (T) this; 98 | } 99 | 100 | public Boolean getDeleteFlag() { 101 | return deleteFlag; 102 | } 103 | 104 | public T setDeleteFlag(Boolean deleteFlag) { 105 | this.deleteFlag = deleteFlag; 106 | return (T) this; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/dao/BaseMapper.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.dao; 2 | 3 | import com.github.yt.mybatis.dao.provider.ModifyProvider; 4 | import com.github.yt.mybatis.dao.provider.RemoveProvider; 5 | import com.github.yt.mybatis.dao.provider.SaveProvider; 6 | import com.github.yt.mybatis.dao.provider.SearchProvider; 7 | import com.github.yt.mybatis.handler.QueryHandler; 8 | import org.apache.ibatis.annotations.*; 9 | 10 | import javax.validation.Valid; 11 | import java.io.Serializable; 12 | import java.util.List; 13 | 14 | 15 | public interface BaseMapper { 16 | 17 | String ENTITY_CLASS = "entityClass"; 18 | String ENTITY = "entity"; 19 | String ENTITIES = "entities"; 20 | String ID = "id"; 21 | String DATA = "data"; 22 | String QUERY_HANDLER = "queryHandler"; 23 | String START = "start"; 24 | String LIMIT = "limit"; 25 | 26 | /** 27 | * 插入一条记录 28 | * 29 | * @param entity 业务实体 30 | */ 31 | @InsertProvider(type = SaveProvider.class, method = "save") 32 | void save(@Param(ENTITY) T entity); 33 | 34 | /** 35 | * 批量插入 36 | * 37 | * @param entities 插入结果集 38 | */ 39 | @InsertProvider(type = SaveProvider.class, method = "saveBatch") 40 | void saveBatch(@Valid @Param(ENTITIES) List entities); 41 | 42 | /** 43 | * 插入非空字段 44 | * 45 | * @param entity 业务实体 46 | */ 47 | @InsertProvider(type = SaveProvider.class, method = "saveForSelective") 48 | void saveForSelective(@Param(ENTITY) T entity); 49 | 50 | /** 51 | * 更新一条记录 52 | * 53 | * @param entity 业务实体 54 | */ 55 | @UpdateProvider(type = ModifyProvider.class, method = "update") 56 | void update(@Param(ENTITY) T entity); 57 | 58 | /** 59 | * 更新非空字段 60 | * 61 | * @param entity 业务实体 62 | */ 63 | @UpdateProvider(type = ModifyProvider.class, method = "updateForSelective") 64 | int updateForSelective(@Param(ENTITY) T entity); 65 | 66 | /** 67 | * 删除 68 | * 69 | * @param entityClass 实体类型 70 | * @param id 主键 71 | */ 72 | @DeleteProvider(type = RemoveProvider.class, method = "delete") 73 | void delete(@Param(ENTITY_CLASS) Class entityClass, @Param(ID) Serializable id); 74 | 75 | /** 76 | * 逻辑删除 77 | * 78 | * @param entityClass 实体类型 79 | * @param id 主键 80 | */ 81 | @DeleteProvider(type = RemoveProvider.class, method = "logicDelete") 82 | void logicDelete(@Param(ENTITY_CLASS) Class entityClass, @Param(ID) Serializable id); 83 | 84 | /** 85 | * 删除 86 | * 87 | * @param id 主键 88 | */ 89 | @SelectProvider(type = SearchProvider.class, method = "findById") 90 | T find(@Param(ENTITY_CLASS) Class entityClass, @Param(ID) Serializable id); 91 | 92 | /** 93 | * 按条件查询记录集合 94 | * 此处来写注解,在子类里面生效 95 | * 96 | * @param entity 实体 97 | * @param queryHandler 查询条件 98 | * @return 查询结果列表 99 | */ 100 | @SelectProvider(type = SearchProvider.class, method = "findAll") 101 | List findAll(@Param(ENTITY) T entity, @Param(QUERY_HANDLER) QueryHandler queryHandler); 102 | 103 | 104 | /** 105 | * 统计分页记录总数 106 | * 107 | * @param entity 实体 108 | * @param queryHandler 查询条件 109 | * @return 实体列表 110 | */ 111 | @SelectProvider(type = SearchProvider.class, method = "pageTotalRecord") 112 | Long pageTotalRecord(@Param(ENTITY) T entity, @Param(QUERY_HANDLER) QueryHandler queryHandler); 113 | 114 | } -------------------------------------------------------------------------------- /src/main/resources/Controller.java.vm: -------------------------------------------------------------------------------- 1 | package ${modulePackage}.controller; 2 | 3 | import javax.annotation.Resource; 4 | 5 | import org.springframework.web.bind.annotation.*; 6 | import com.github.yt.mybatis.handler.QueryHandler; 7 | import com.github.yt.web.controller.BaseController; 8 | import com.github.yt.web.result.HttpResultEntity; 9 | import com.github.yt.web.result.HttpResultHandler; 10 | import io.swagger.annotations.ApiOperation; 11 | import io.swagger.annotations.ApiParam; 12 | import ${importPackage}.domain.${className}; 13 | import ${importPackage}.service.${replaceSuffixClassName}Service; 14 | 15 | 16 | /** 17 | * ${codeName}控制器 18 | * 19 | */ 20 | @RestController 21 | @RequestMapping("/${replaceSuffixLowerName}") 22 | public class ${replaceSuffixClassName}Controller extends BaseController { 23 | 24 | 25 | /** 26 | * ${codeName}服务类 27 | */ 28 | @Resource 29 | private ${replaceSuffixClassName}Service ${replaceSuffixLowerName}Service; 30 | 31 | /** 32 | * 添加${codeName} 33 | */ 34 | @ApiOperation(value = "add ${lowerName}", notes = "add ${lowerName} notes", response = ${className}.class) 35 | @RequestMapping(value = "/add", method = RequestMethod.POST) 36 | public HttpResultEntity add(@ApiParam(value = "${lowerName}", required = true) @RequestBody ${className} ${lowerName}){ 37 | ${replaceSuffixLowerName}Service.save(${lowerName}); 38 | return HttpResultHandler.getSuccessResult(); 39 | } 40 | 41 | /** 42 | * 更新${codeName} 43 | */ 44 | @ApiOperation(value = "update ${lowerName}", notes = "update ${lowerName} notes", response = ${className}.class) 45 | @RequestMapping(value = "/update", method = RequestMethod.PUT) 46 | public HttpResultEntity update(@ApiParam(value = "${lowerName}", required = true) @RequestBody ${className} ${lowerName}) { 47 | ${replaceSuffixLowerName}Service.updateForSelective(${lowerName}); 48 | return HttpResultHandler.getSuccessResult(); 49 | } 50 | 51 | /** 52 | * 删除${codeName} 53 | */ 54 | @ApiOperation(value = "delete") 55 | @RequestMapping(value = "/delete/{${prikey}}", method = RequestMethod.DELETE) 56 | public HttpResultEntity delete(@PathVariable String ${prikey}){ 57 | ${replaceSuffixLowerName}Service.delete(${className}.class, ${prikey}); 58 | return HttpResultHandler.getSuccessResult(); 59 | } 60 | 61 | /** 62 | * 通过id查询${codeName} 63 | */ 64 | @ApiOperation(value = "通过id查询${codeName}") 65 | @RequestMapping(value = "/find/{${prikey}}", method = RequestMethod.GET) 66 | public HttpResultEntity find(@PathVariable String ${prikey}) throws Exception { 67 | return HttpResultHandler.getSuccessResult(${replaceSuffixLowerName}Service.find(${className}.class, ${prikey})); 68 | } 69 | 70 | /** 71 | * findAll${codeName} 72 | */ 73 | @ApiOperation(value = "findAll${codeName}") 74 | @RequestMapping(value = "/findAll", method = RequestMethod.GET) 75 | public HttpResultEntity findAll(${className} ${lowerName},QueryHandler queryHandle) throws Exception { 76 | return HttpResultHandler.getSuccessResult(${replaceSuffixLowerName}Service.findAll(${lowerName}, queryHandle.addOrderBy("createDateTime", "desc"))); 77 | } 78 | 79 | /** 80 | * 分页查询${codeName} 81 | */ 82 | @ApiOperation(value = "分页查询${codeName}") 83 | @RequestMapping(value = "/getData", method = RequestMethod.GET) 84 | public HttpResultEntity getData(${className} ${lowerName},QueryHandler queryHandle) throws Exception { 85 | return HttpResultHandler.getSuccessResult(${replaceSuffixLowerName}Service.getData(${lowerName}, queryHandle.addOrderBy("createDateTime", "desc"))); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/handler/QueryHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.handler; 2 | 3 | import com.github.yt.mybatis.config.page.PageConfiguration; 4 | import org.apache.commons.lang3.StringUtils; 5 | import org.springframework.web.context.request.RequestContextHolder; 6 | import org.springframework.web.context.request.ServletRequestAttributes; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import java.util.*; 10 | 11 | 12 | public class QueryHandler { 13 | 14 | //是否使用distinct 15 | private Boolean distinct; 16 | //扩展的whereSql 17 | private List whereSqls = new ArrayList<>(); 18 | 19 | private LinkedHashMap orderBy = new LinkedHashMap(); 20 | //扩展数据 21 | private Map expandData = new HashMap<>(); 22 | 23 | private LinkedList sqlJoinHandler = new LinkedList<>(); 24 | 25 | private Integer start; 26 | 27 | private Integer limit; 28 | 29 | //指定查询列sql,例如“ t.name,t.pass” 30 | protected String selectColumnSql; 31 | 32 | public QueryHandler setSelectColumnSql(String sql) { 33 | if (StringUtils.isNotEmpty(sql)) { 34 | this.selectColumnSql = sql; 35 | } 36 | return this; 37 | } 38 | 39 | public QueryHandler addWhereSql(String whereSql) { 40 | if (StringUtils.isNotEmpty(whereSql)) { 41 | whereSqls.add(whereSql); 42 | } 43 | return this; 44 | } 45 | 46 | public QueryHandler addOrderBy(String key, String value) { 47 | orderBy.put(key, value); 48 | return this; 49 | } 50 | 51 | public QueryHandler addDistinct() { 52 | distinct = true; 53 | return this; 54 | } 55 | 56 | public Boolean getDistinct() { 57 | return distinct; 58 | } 59 | 60 | public QueryHandler addExpandData(String key, Object value) { 61 | expandData.put(key, value); 62 | return this; 63 | } 64 | 65 | public Map getExpandData() { 66 | return expandData; 67 | } 68 | 69 | public String getSelectColumnSql() { 70 | return selectColumnSql; 71 | } 72 | 73 | 74 | public Integer getStart() { 75 | return start; 76 | } 77 | 78 | public QueryHandler setStart(Integer start) { 79 | this.start = start; 80 | return this; 81 | } 82 | 83 | public Integer getLimit() { 84 | return limit; 85 | } 86 | 87 | public QueryHandler setLimit(Integer limit) { 88 | this.limit = limit; 89 | return this; 90 | } 91 | 92 | public QueryHandler configPage() { 93 | PageConfiguration.create().convert(this, getHttpServletRequest()); 94 | return this; 95 | } 96 | 97 | public QueryHandler addJoinHandle(String selectColumns, SQLJoinHandler.JoinType joinType, String joinSql) { 98 | sqlJoinHandler.add(new SQLJoinHandler(selectColumns, joinType, joinSql)); 99 | return this; 100 | } 101 | 102 | protected static HttpServletRequest getHttpServletRequest() { 103 | ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 104 | return attributes == null ? null : attributes.getRequest(); 105 | } 106 | 107 | public static String getInSql(String fieldName, int querySize) { 108 | if (querySize == 0) { 109 | return " (null) "; 110 | } 111 | String str = ""; 112 | for (int i = 0; i < querySize; i++) { 113 | str = str + ",#{" + fieldName + "[" + i + "]}"; 114 | } 115 | return "(" + str.replaceFirst(",", "") + ")"; 116 | } 117 | } 118 | 119 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/generator/CommonPageParser.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.generator; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.apache.velocity.Template; 6 | import org.apache.velocity.VelocityContext; 7 | import org.apache.velocity.app.Velocity; 8 | import org.apache.velocity.app.VelocityEngine; 9 | 10 | import java.io.BufferedWriter; 11 | import java.io.File; 12 | import java.io.FileOutputStream; 13 | import java.io.OutputStreamWriter; 14 | import java.util.Properties; 15 | 16 | 17 | public class CommonPageParser { 18 | 19 | private static VelocityEngine ve; 20 | 21 | private final static String CONTENT_ENCODING = "UTF-8"; 22 | 23 | private static final Log log = LogFactory.getLog(CommonPageParser.class); 24 | 25 | private static boolean isReplace = true; 26 | 27 | public static String getRootPath() { 28 | String rootPath = ""; 29 | try { 30 | File file = new File(CommonPageParser.class.getResource("/").getFile()); 31 | rootPath = file.getParent(); 32 | rootPath = java.net.URLDecoder.decode(rootPath.substring(0, rootPath.indexOf("target") - 1), "utf-8"); 33 | return rootPath; 34 | } catch (Exception e) { 35 | e.printStackTrace(); 36 | } 37 | return rootPath; 38 | } 39 | 40 | public static void main(String[] args) { 41 | System.out.println(getRootPath()); 42 | } 43 | 44 | static { 45 | try { 46 | String templateBasePath = CommonPageParser.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 47 | Properties properties = new Properties(); 48 | if (templateBasePath.endsWith(".jar")) { 49 | properties.setProperty(Velocity.RESOURCE_LOADER, "jar"); 50 | properties.setProperty("jar.resource.loader.class", "org.apache.velocity.runtime.resource.loader.JarResourceLoader"); 51 | properties.setProperty("jar.resource.loader.path", "jar:file:" + templateBasePath); 52 | } else { 53 | properties.setProperty(Velocity.RESOURCE_LOADER, "file"); 54 | properties.setProperty("file.resource.loader.description", "Velocity File Resource Loader"); 55 | properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templateBasePath); 56 | properties.setProperty(Velocity.FILE_RESOURCE_LOADER_CACHE, "true"); 57 | } 58 | properties.setProperty("file.resource.loader.modificationCheckInterval", "30"); 59 | properties.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM_CLASS, 60 | "org.apache.velocity.runtime.log.Log4JLogChute"); 61 | properties.setProperty("runtime.log.logsystem.log4j.logger", "org.apache.velocity"); 62 | properties.setProperty("directive.set.null.allowed", "true"); 63 | VelocityEngine velocityEngine = new VelocityEngine(); 64 | velocityEngine.init(properties); 65 | ve = velocityEngine; 66 | } catch (Exception e) { 67 | log.error(e); 68 | } 69 | } 70 | 71 | public static void WriterPage(VelocityContext context, String templateName, String fileDirPath, String targetFile) { 72 | try { 73 | File file = new File(fileDirPath + targetFile); 74 | if (!file.exists()) { 75 | new File(file.getParent()).mkdirs(); 76 | } else { 77 | if (isReplace) { 78 | System.out.println("替换文件" + file.getAbsolutePath()); 79 | } else { 80 | System.out.println("页面生成失败" + file.getAbsolutePath() + "文件已存在"); 81 | return; 82 | } 83 | } 84 | Template template = ve.getTemplate(templateName, CONTENT_ENCODING); 85 | FileOutputStream fos = new FileOutputStream(file); 86 | BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, CONTENT_ENCODING)); 87 | template.merge(context, writer); 88 | writer.flush(); 89 | writer.close(); 90 | fos.close(); 91 | System.out.println("页面生成成功" + file.getAbsolutePath()); 92 | } catch (Exception e) { 93 | log.error("", e); 94 | } 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/utils/DateTimeFormatter.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.utils; 2 | 3 | 4 | import com.github.yt.base.exception.BaseErrorException; 5 | 6 | import java.text.ParseException; 7 | import java.text.SimpleDateFormat; 8 | import java.util.Date; 9 | 10 | // date time utils 11 | public class DateTimeFormatter { 12 | 13 | public final String SHORT_DATE = "MM-dd"; 14 | public final String SHORT_TIME = "HH:mm"; 15 | public final String SHORT_DATE_TIME = "yyyy-MM-dd HH:mm"; 16 | public final String FULL_DATE = "yyyy-MM-dd"; 17 | public final String FULL_TIME = "HH:mm:ss"; 18 | public final String FULL_DATE_TIME = "yyyy-MM-dd HH:mm:ss"; 19 | 20 | public final SimpleDateFormat SD = new SimpleDateFormat(SHORT_DATE); 21 | public final SimpleDateFormat ST = new SimpleDateFormat(SHORT_TIME); 22 | public final SimpleDateFormat SDT = new SimpleDateFormat(SHORT_DATE_TIME); 23 | public final SimpleDateFormat FD = new SimpleDateFormat(FULL_DATE); 24 | public final SimpleDateFormat FT = new SimpleDateFormat(FULL_TIME); 25 | public final SimpleDateFormat FDT = new SimpleDateFormat(FULL_DATE_TIME); 26 | 27 | public String sd() { 28 | return SD.format(new Date()); 29 | } 30 | 31 | public String st() { 32 | return ST.format(new Date()); 33 | } 34 | 35 | public String sdt() { 36 | return SDT.format(new Date()); 37 | } 38 | 39 | public String fd() { 40 | return FD.format(new Date()); 41 | } 42 | 43 | public String ft() { 44 | return FT.format(new Date()); 45 | } 46 | 47 | public String fdt() { 48 | return FDT.format(new Date()); 49 | } 50 | 51 | public String sd(Date date) { 52 | return SD.format(date); 53 | } 54 | 55 | public String st(Date date) { 56 | return ST.format(date); 57 | } 58 | 59 | public String sdt(Date date) { 60 | return SDT.format(date); 61 | } 62 | 63 | public String fd(Date date) { 64 | return FD.format(date); 65 | } 66 | 67 | public String ft(Date date) { 68 | return FT.format(date); 69 | } 70 | 71 | public String fdt(Date date) { 72 | return FDT.format(date); 73 | } 74 | 75 | public Date sd(String source) { 76 | try { 77 | return SD.parse(source); 78 | } catch (ParseException e) { 79 | throw new BaseErrorException(e); 80 | } 81 | } 82 | 83 | public Date st(String source) { 84 | try { 85 | return ST.parse(source); 86 | } catch (ParseException e) { 87 | throw new BaseErrorException(e); 88 | } 89 | } 90 | 91 | public Date sdt(String source) { 92 | try { 93 | return SDT.parse(source); 94 | } catch (ParseException e) { 95 | throw new BaseErrorException(e); 96 | } 97 | } 98 | 99 | public Date fd(String source) { 100 | try { 101 | return FD.parse(source); 102 | } catch (ParseException e) { 103 | throw new BaseErrorException(e); 104 | } 105 | } 106 | 107 | public Date ft(String source) { 108 | try { 109 | return FT.parse(source); 110 | } catch (ParseException e) { 111 | throw new BaseErrorException(e); 112 | } 113 | } 114 | 115 | public Date fdt(String source) { 116 | try { 117 | return FDT.parse(source); 118 | } catch (ParseException e) { 119 | throw new BaseErrorException(e); 120 | } 121 | } 122 | 123 | /** 124 | * 判断某个时间类型是否是对应的格式 125 | * 126 | * @param dateStr 时间串,例如'2016-02-17' 127 | * @param format 格式,例如'yyyy-MM-dd' 128 | * @return boolean 129 | */ 130 | public static boolean isValidFormatDate(String dateStr, String format) { 131 | Boolean flag = true; 132 | try { 133 | SimpleDateFormat sdf = new SimpleDateFormat(format); 134 | sdf.setLenient(false); 135 | sdf.parse(dateStr); 136 | } catch (Exception e) { 137 | flag = false; 138 | } 139 | return flag; 140 | } 141 | 142 | /** 143 | * 判断某个时间类型是否是对应的格式 144 | * 145 | * @param dateStr 时间串,例如'2016-02-17' 146 | * @return boolean 147 | */ 148 | public static boolean isYYYYMMddFormatDate(String dateStr) { 149 | return isValidFormatDate(dateStr, "yyyy-MM-dd"); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/dao/provider/SaveProvider.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.dao.provider; 2 | 3 | 4 | import com.github.yt.base.exception.BaseErrorException; 5 | import com.github.yt.mybatis.dao.BaseMapper; 6 | import com.github.yt.mybatis.dao.MapperProvider; 7 | import com.github.yt.mybatis.domain.BaseEntity; 8 | import com.github.yt.mybatis.utils.JPAUtils; 9 | import org.apache.commons.lang3.StringUtils; 10 | 11 | import javax.persistence.Id; 12 | import javax.persistence.Transient; 13 | import java.lang.reflect.Field; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.UUID; 17 | 18 | import static com.github.yt.mybatis.mybatis.SqlBuilder.*; 19 | 20 | 21 | public class SaveProvider extends MapperProvider { 22 | 23 | public String save(Map param) { 24 | Class entityClass = param.get(BaseMapper.ENTITY).getClass(); 25 | begin(); 26 | INSERT_INTO(getTableName(entityClass)); 27 | Field idField = null; 28 | for (Field field : JPAUtils.getAllFields(entityClass)) { 29 | field.setAccessible(true); 30 | if (null != field.getAnnotation(Id.class) || null != field.getAnnotation(Transient.class)) { 31 | idField = field; 32 | continue; 33 | } 34 | String fieldName = JPAUtils.getAnnotationColumnName(field); 35 | Object value = JPAUtils.getValue(param.get(BaseMapper.ENTITY), field.getName()); 36 | if (null == value) { 37 | continue; 38 | } 39 | VALUES(fieldName, StringUtils.join("#{", BaseMapper.ENTITY, ".", field.getName(), "}")); 40 | } 41 | if (null == idField) { 42 | throw new BaseErrorException(StringUtils.join(entityClass.getName(), "实体未配置@Id ")); 43 | } 44 | setId(param, idField); 45 | return sql(); 46 | } 47 | 48 | public String saveBatch(Map param) { 49 | if (null == param.get(BaseMapper.ENTITIES)) { 50 | throw new BaseErrorException("批量插入的数据为null"); 51 | } 52 | Class entityClass = ((List) param.get(BaseMapper.ENTITIES)).get(0).getClass(); 53 | begin(); 54 | BATCH_INSERT_INTO(getTableName(entityClass)); 55 | Field idField = null; 56 | for (int i = 0; i < ((List) param.get(BaseMapper.ENTITIES)).size(); i++) { 57 | for (Field field : JPAUtils.getAllFields(entityClass)) { 58 | field.setAccessible(true); 59 | if (null != field.getAnnotation(Id.class) || null != field.getAnnotation(Transient.class)) { 60 | idField = field; 61 | continue; 62 | } 63 | String fieldName = JPAUtils.getAnnotationColumnName(field); 64 | Object value = JPAUtils.getValue(((List) param.get(BaseMapper.ENTITIES)).get(i), field.getName()); 65 | if (null == value) { 66 | continue; 67 | } 68 | BATCH_VALUES(fieldName, StringUtils.join("#{", BaseMapper.ENTITIES, "[", i, "]", ".", field.getName(), "}")); 69 | } 70 | if (null == idField) { 71 | throw new BaseErrorException(StringUtils.join(entityClass.getName(), "实体未配置@Id ")); 72 | } 73 | setIdBatch((BaseEntity) ((List) param.get(BaseMapper.ENTITIES)).get(i), i, idField); 74 | BATCH_SEGMENTATION(); 75 | } 76 | return sql(); 77 | } 78 | 79 | public String saveForSelective(Map param) { 80 | Class entityClass = param.get(BaseMapper.ENTITY).getClass(); 81 | begin(); 82 | INSERT_INTO(getTableName(entityClass)); 83 | Field idField = null; 84 | for (Field field : JPAUtils.getAllFields(entityClass)) { 85 | field.setAccessible(true); 86 | if (null != field.getAnnotation(Id.class) || null != field.getAnnotation(Transient.class)) { 87 | idField = field; 88 | continue; 89 | } 90 | try { 91 | String fieldName = JPAUtils.getAnnotationColumnName(field); 92 | if (field.get(param.get(BaseMapper.ENTITY)) != null) { 93 | VALUES(fieldName, StringUtils.join("#{", BaseMapper.ENTITY, ".", field.getName(), "}")); 94 | } 95 | } catch (IllegalAccessException e) { 96 | throw new BaseErrorException(e); 97 | } 98 | } 99 | if (null == idField) { 100 | throw new BaseErrorException(StringUtils.join(entityClass.getName(), "实体未配置@Id ")); 101 | } 102 | setId(param, idField); 103 | return sql(); 104 | } 105 | 106 | private void setId(Map param, Field idField) { 107 | if (!idField.getType().isAssignableFrom(String.class)) { 108 | return; 109 | } 110 | try { 111 | String fieldName = JPAUtils.getAnnotationColumnName(idField); 112 | if (StringUtils.isNotEmpty((String) idField.get(param.get(BaseMapper.ENTITY)))) { 113 | VALUES(fieldName, StringUtils.join("#{", BaseMapper.ENTITY, ".", idField.getName(), "}")); 114 | return; 115 | } 116 | String id = UUID.randomUUID().toString().replace("-", ""); 117 | VALUES(fieldName, StringUtils.join("'", id, "'")); 118 | idField.set(param.get(BaseMapper.ENTITY), id); 119 | } catch (IllegalAccessException e) { 120 | throw new BaseErrorException(e); 121 | } 122 | } 123 | 124 | private void setIdBatch(BaseEntity baseEntity, int i, Field idField) { 125 | if (!idField.getType().isAssignableFrom(String.class)) { 126 | return; 127 | } 128 | try { 129 | String fieldName = JPAUtils.getAnnotationColumnName(idField); 130 | if (StringUtils.isNotEmpty((String) idField.get(baseEntity))) { 131 | BATCH_VALUES(fieldName, StringUtils.join("#{", BaseMapper.ENTITIES, "[", i, "]", ".", idField.getName(), "}")); 132 | return; 133 | } 134 | String id = UUID.randomUUID().toString().replace("-", ""); 135 | BATCH_VALUES(fieldName, StringUtils.join("'", id, "'")); 136 | idField.set(baseEntity, id); 137 | } catch (IllegalAccessException e) { 138 | throw new BaseErrorException(e); 139 | } 140 | } 141 | 142 | } 143 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/service/impl/ServiceSupport.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.service.impl; 2 | 3 | import com.github.yt.mybatis.config.fields.FieldsConfiguration; 4 | import com.github.yt.mybatis.config.fields.FieldsDefault; 5 | import com.github.yt.mybatis.dao.BaseMapper; 6 | import com.github.yt.mybatis.domain.BaseEntity; 7 | import com.github.yt.mybatis.handler.QueryHandler; 8 | import com.github.yt.mybatis.result.QueryResult; 9 | import com.github.yt.mybatis.service.BaseService; 10 | import com.github.yt.mybatis.utils.JPAUtils; 11 | import org.apache.commons.collections4.CollectionUtils; 12 | import org.apache.commons.lang3.StringUtils; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | import org.springframework.web.context.request.RequestContextHolder; 16 | import org.springframework.web.context.request.ServletRequestAttributes; 17 | 18 | import java.io.Serializable; 19 | import java.util.ArrayList; 20 | import java.util.Date; 21 | import java.util.List; 22 | 23 | 24 | public abstract class ServiceSupport> implements BaseService { 25 | 26 | protected Logger logger = LoggerFactory.getLogger(this.getClass()); 27 | 28 | public abstract M getMapper(); 29 | 30 | @Override 31 | public void save(T entity) { 32 | this.processCreateColumns(entity); 33 | getMapper().save(entity); 34 | } 35 | 36 | @Override 37 | public void saveBatch(List entities) { 38 | if (CollectionUtils.isEmpty(entities)) { 39 | return; 40 | } 41 | if (BaseEntity.class.isAssignableFrom(entities.get(0).getClass())) { 42 | for (T entity : entities) { 43 | this.processCreateColumns(entity); 44 | } 45 | } 46 | getMapper().saveBatch(entities); 47 | } 48 | 49 | @Override 50 | public void saveForSelective(T entity) { 51 | this.processCreateColumns(entity); 52 | getMapper().saveForSelective(entity); 53 | } 54 | 55 | @Override 56 | public void update(T entity) { 57 | if (null == JPAUtils.gtIdValue(entity)) { 58 | return; 59 | } 60 | processModifyColumns(entity); 61 | getMapper().update(entity); 62 | } 63 | 64 | @Override 65 | public void updateForSelective(T entity) { 66 | if (null == JPAUtils.gtIdValue(entity)) { 67 | return; 68 | } 69 | this.processModifyColumns(entity); 70 | getMapper().updateForSelective(entity); 71 | } 72 | 73 | @Override 74 | public void delete(Class clazz, Serializable id) { 75 | getMapper().delete(clazz, id); 76 | } 77 | 78 | @Override 79 | public void logicDelete(Class clazz, Serializable id) { 80 | getMapper().logicDelete(clazz, id); 81 | } 82 | 83 | @Override 84 | public T find(Class clazz, Serializable id) { 85 | return getMapper().find(clazz, id); 86 | } 87 | 88 | @Override 89 | public List findAll(T entity) { 90 | return getMapper().findAll(entity, new QueryHandler()); 91 | } 92 | 93 | @Override 94 | public List findAll(T entity, QueryHandler queryHandler) { 95 | return getMapper().findAll(entity, queryHandler == null ? new QueryHandler() : queryHandler); 96 | } 97 | 98 | @Override 99 | public QueryResult getData(T entity, QueryHandler queryHandle) { 100 | QueryResult qr = new QueryResult(); 101 | if (queryHandle == null) { 102 | queryHandle = new QueryHandler(); 103 | } 104 | qr.setRecordsTotal(getMapper().pageTotalRecord(entity, queryHandle)); 105 | if (qr.getRecordsTotal() == 0) { 106 | qr.setData(new ArrayList()); 107 | return qr; 108 | } 109 | qr.setData(getMapper().findAll(entity, queryHandle)); 110 | return qr; 111 | } 112 | 113 | private Object getSessionAttr(String attr) { 114 | return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession() 115 | .getAttribute(attr); 116 | } 117 | 118 | private void setFounder(BaseEntity entity) { 119 | FieldsDefault fieldsDefault = FieldsConfiguration.create(); 120 | try { 121 | if (StringUtils.isEmpty(entity.getFounderId())) { 122 | entity.setFounderId(fieldsDefault.getOperatorId()); 123 | } 124 | if (StringUtils.isEmpty(entity.getFounderName())) { 125 | entity.setFounderName(fieldsDefault.getOperator()); 126 | } 127 | } catch (Exception e) { 128 | logger.debug("setFounder时session获取失败!"); 129 | entity.setFounderId(fieldsDefault.getOperatorId()); 130 | entity.setFounderName(fieldsDefault.getOperator()); 131 | } 132 | } 133 | 134 | private void setModifyFounder(BaseEntity entity) { 135 | FieldsDefault fieldsDefault = FieldsConfiguration.create(); 136 | try { 137 | if (StringUtils.isEmpty(entity.getModifierId())) { 138 | entity.setFounderId(fieldsDefault.getModifyOperatorId()); 139 | } 140 | if (StringUtils.isEmpty(entity.getModifierName())) { 141 | entity.setFounderName(fieldsDefault.getModifyOperator()); 142 | } 143 | } catch (Exception e) { 144 | logger.info("update时session获取失败!"); 145 | entity.setModifierId(fieldsDefault.getModifyOperatorId()); 146 | entity.setModifierName(fieldsDefault.getModifyOperator()); 147 | } 148 | } 149 | 150 | private void processCreateColumns(T entity) { 151 | if (entity instanceof BaseEntity) { 152 | BaseEntity baseEntity = ((BaseEntity) entity); 153 | if (baseEntity.getCreateDateTime() == null) { 154 | baseEntity.setCreateDateTime(new Date()); 155 | } 156 | if (baseEntity.getModifyDateTime() == null) { 157 | baseEntity.setModifyDateTime(baseEntity.getCreateDateTime()); 158 | } 159 | setFounder((BaseEntity) entity); 160 | } 161 | } 162 | 163 | private void processModifyColumns(T entity) { 164 | if (entity instanceof BaseEntity) { 165 | BaseEntity baseEntity = ((BaseEntity) entity); 166 | if (baseEntity.getModifyDateTime() == null) { 167 | baseEntity.setModifyDateTime(new Date()); 168 | } 169 | this.setModifyFounder((BaseEntity) entity); 170 | } 171 | } 172 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.github.limiaogithub 5 | yt_mybatis 6 | 3.0.1 7 | https://github.com/limiaogithub/yt_mybatis 8 | yt_mybatis 9 | CURD on mybaits 10 | 11 | scm:git@github.com:limiaogithub/yt_mybatis.git 12 | scm:git@github.com:limiaogithub/yt_mybatis.git 13 | git@github.com:limiaogithub/yt_mybatis.git 14 | 15 | 16 | 17 | The Apache Software License, Version 2.0 18 | http://www.apache.org/licenses/LICENSE-2.0.txt 19 | 20 | 21 | 22 | 23 | limiao 24 | 18640290294@163.com 25 | 26 | 27 | 28 | 29 | javax 30 | javaee-api 31 | 7.0 32 | compile 33 | 34 | 35 | org.mybatis 36 | mybatis 37 | 3.4.5 38 | 39 | 40 | org.mybatis 41 | mybatis-spring 42 | 1.3.1 43 | 44 | 45 | com.fasterxml.jackson.core 46 | jackson-annotations 47 | 2.8.8 48 | 49 | 50 | com.alibaba 51 | fastjson 52 | 1.2.6 53 | 54 | 55 | org.apache.velocity 56 | velocity 57 | 1.7 58 | compile 59 | 60 | 61 | commons-beanutils 62 | commons-beanutils 63 | 1.9.2 64 | 65 | 66 | org.apache.commons 67 | commons-lang3 68 | 3.1 69 | 70 | 71 | org.apache.commons 72 | commons-collections4 73 | 4.0 74 | 75 | 76 | org.slf4j 77 | slf4j-api 78 | 1.7.12 79 | 80 | 81 | org.springframework 82 | spring-web 83 | 4.3.10.RELEASE 84 | 85 | 86 | com.github.limiaogithub 87 | yt_base 88 | 1.0.0 89 | 90 | 91 | 92 | 93 | 94 | org.apache.maven.plugins 95 | maven-compiler-plugin 96 | 3.3 97 | 98 | UTF-8 99 | 1.8 100 | 1.8 101 | 102 | 103 | 104 | org.sonatype.plugins 105 | nexus-staging-maven-plugin 106 | 1.6.3 107 | true 108 | 109 | release 110 | https://oss.sonatype.org/ 111 | true 112 | 113 | 114 | 115 | org.apache.maven.plugins 116 | maven-javadoc-plugin 117 | 2.10.3 118 | 119 | 120 | attach-javadocs 121 | 122 | jar 123 | 124 | 125 | 126 | 127 | 128 | org.apache.maven.plugins 129 | maven-source-plugin 130 | 131 | 132 | attach-sources 133 | 134 | jar-no-fork 135 | 136 | 137 | 138 | 139 | 140 | org.apache.maven.plugins 141 | maven-gpg-plugin 142 | 1.6 143 | 144 | 145 | sign-artifacts 146 | verify 147 | 148 | sign 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | release 158 | https://oss.sonatype.org/content/repositories/snapshots 159 | 160 | 161 | release 162 | Maven Central Staging Repository 163 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 164 | 165 | 166 | 167 | 168 | jdk18 169 | 170 | true 171 | 1.8 172 | 173 | 174 | 1.8 175 | 1.8 176 | 1.8 177 | 178 | 179 | 180 | 181 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/utils/JPAUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.utils; 2 | 3 | import com.github.yt.base.exception.BaseErrorException; 4 | import org.apache.commons.collections4.CollectionUtils; 5 | import org.apache.commons.lang3.StringUtils; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import javax.persistence.Column; 10 | import javax.persistence.Id; 11 | import javax.persistence.Transient; 12 | import java.lang.reflect.Field; 13 | import java.util.*; 14 | 15 | 16 | public class JPAUtils { 17 | 18 | private static Logger logger = LoggerFactory.getLogger(JPAUtils.class); 19 | 20 | public static List getAllFields(Class entityClass) { 21 | Field[] fields = entityClass.getDeclaredFields(); 22 | return getAllFields(entityClass.getSuperclass(), new ArrayList<>(Arrays.asList(fields))); 23 | } 24 | 25 | private static List getAllFields(Class entityClass, List fields) { 26 | if (Object.class.equals(entityClass)) { 27 | Iterator it = fields.iterator(); 28 | while (it.hasNext()) { 29 | Field next = it.next(); 30 | if ("serialVersionUID".equals(next.getName())) { 31 | it.remove(); 32 | continue; 33 | } 34 | if (null != next.getAnnotation(Transient.class)) { 35 | it.remove(); 36 | } 37 | } 38 | return fields; 39 | } 40 | Collections.addAll(fields, entityClass.getDeclaredFields()); 41 | return getAllFields(entityClass.getSuperclass(), fields); 42 | } 43 | 44 | public static Field getIdField(Class entityClass) { 45 | for (Class c = entityClass; c != Object.class; c = c.getSuperclass()) { 46 | Field[] fields = c.getDeclaredFields(); 47 | for (Field field : fields) { 48 | if (null != field.getAnnotation(Id.class)) { 49 | return field; 50 | } 51 | } 52 | } 53 | throw new BaseErrorException("Id field is not found in[" + entityClass + "]" + entityClass.getName()); 54 | } 55 | 56 | public static Object gtIdValue(Object po) { 57 | if (null == po) { 58 | return null; 59 | } 60 | return getValue(po, getIdField(po.getClass())); 61 | } 62 | 63 | public static Object getValue(Object po, String fieldName) { 64 | if (null == po || StringUtils.isEmpty(fieldName)) { 65 | throw new BaseErrorException("parameter is null"); 66 | } 67 | try { 68 | Field field = getField(po.getClass(), fieldName); 69 | field.setAccessible(true); 70 | return field.get(po); 71 | } catch (Exception e) { 72 | throw new BaseErrorException(e); 73 | } 74 | } 75 | 76 | public static Field getField(Class clazz, String fieldName) { 77 | if (clazz == Object.class) { 78 | throw new BaseErrorException("class does not have this field :" + fieldName); 79 | } 80 | for (Field field : clazz.getDeclaredFields()) { 81 | if (field.getName().equals(fieldName)) { 82 | return field; 83 | } 84 | } 85 | return getField(clazz.getSuperclass(), fieldName); 86 | } 87 | 88 | public static void setValue(Object source, String fieldName, Object value) { 89 | if (null == source || StringUtils.isEmpty(fieldName)) { 90 | throw new BaseErrorException("parameter is null"); 91 | } 92 | try { 93 | Field field = getField(source.getClass(), fieldName); 94 | field.setAccessible(true); 95 | field.set(source, value); 96 | } catch (Exception e) { 97 | throw new BaseErrorException(e); 98 | } 99 | 100 | } 101 | 102 | public static Object getValue(Object source, Field field) { 103 | try { 104 | field.setAccessible(true); 105 | return field.get(source); 106 | } catch (Exception e) { 107 | logger.error("JPAUtils getValue 异常!", e); 108 | return null; 109 | } 110 | } 111 | 112 | public static Map getIdPropertyMap(String propertyName, Collection entityCollection) { 113 | Map result = new LinkedHashMap<>(); 114 | if (CollectionUtils.isNotEmpty(entityCollection)) { 115 | for (T entity : entityCollection) { 116 | try { 117 | Field idField = getIdField(entity.getClass()); 118 | idField.setAccessible(true); 119 | Object propertyObj = getValue(entity, entity.getClass().getDeclaredField(propertyName)); 120 | result.put((String) idField.get(entity), propertyObj); 121 | } catch (Exception e) { 122 | logger.error("JPAUtils getValue 异常!", e); 123 | return null; 124 | } 125 | } 126 | } 127 | return result; 128 | } 129 | 130 | public static Map getIdEntityMap(Collection entityCollection) { 131 | Map result = new LinkedHashMap<>(); 132 | if (CollectionUtils.isNotEmpty(entityCollection)) { 133 | for (T entity : entityCollection) { 134 | try { 135 | Field idField = getIdField(entity.getClass()); 136 | result.put((String) getValue(entity, idField), entity); 137 | } catch (BaseErrorException e) { 138 | e.printStackTrace(); 139 | } 140 | } 141 | } 142 | return result; 143 | } 144 | 145 | public static Map propertyEntityMap(String propertyName, Collection entityCollection) { 146 | Map result = new LinkedHashMap<>(); 147 | if (CollectionUtils.isNotEmpty(entityCollection)) { 148 | for (T entity : entityCollection) { 149 | try { 150 | Field propertyField = entity.getClass().getDeclaredField(propertyName); 151 | result.put(getValue(entity, propertyField), entity); 152 | } catch (NoSuchFieldException e) { 153 | logger.error("JPAUtils getValue 异常!", e); 154 | return null; 155 | } 156 | } 157 | } 158 | return result; 159 | } 160 | 161 | public static String getAnnotationColumnName(Field field) { 162 | Column columnAnnotation = field.getAnnotation(Column.class); 163 | if (columnAnnotation == null || StringUtils.isEmpty(columnAnnotation.name())) { 164 | return field.getName(); 165 | } 166 | return columnAnnotation.name(); 167 | } 168 | 169 | public static String getSearchAnnotationColumnName(Field field) { 170 | return getSearchAnnotationColumnName(field, ""); 171 | } 172 | 173 | public static String getSearchAnnotationColumnName(Field field, String aliasName) { 174 | Column columnAnnotation = field.getAnnotation(Column.class); 175 | if (columnAnnotation == null || StringUtils.isEmpty(columnAnnotation.name())) { 176 | return aliasName + field.getName(); 177 | } 178 | return aliasName + columnAnnotation.name() + " as " + field.getName(); 179 | } 180 | 181 | public static String getSelectSql(Class entityClass) { 182 | return getSelectSql(entityClass, ""); 183 | } 184 | 185 | public static String getSelectSql(Class entityClass, String aliasName) { 186 | String selectSql = ""; 187 | for (Field field : JPAUtils.getAllFields(entityClass)) { 188 | field.setAccessible(true); 189 | String fieldName = JPAUtils.getSearchAnnotationColumnName(field, aliasName); 190 | if (StringUtils.isNotEmpty(fieldName)) { 191 | selectSql = selectSql + "," + fieldName + ""; 192 | } 193 | } 194 | selectSql = selectSql.replaceFirst(",", ""); 195 | if (StringUtils.isEmpty(selectSql)) { 196 | return aliasName + "*"; 197 | } 198 | return selectSql; 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/dao/provider/SearchProvider.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.dao.provider; 2 | 3 | 4 | import com.github.yt.base.exception.BaseErrorException; 5 | import com.github.yt.mybatis.dao.BaseMapper; 6 | import com.github.yt.mybatis.dao.MapperProvider; 7 | import com.github.yt.mybatis.handler.QueryHandler; 8 | import com.github.yt.mybatis.handler.SQLJoinHandler; 9 | import com.github.yt.mybatis.utils.BeanUtils; 10 | import com.github.yt.mybatis.utils.ChainMap; 11 | import com.github.yt.mybatis.utils.JPAUtils; 12 | import org.apache.commons.collections4.MapUtils; 13 | import org.apache.commons.lang3.StringUtils; 14 | 15 | import javax.persistence.Table; 16 | import javax.persistence.Transient; 17 | import java.lang.reflect.Field; 18 | import java.util.LinkedHashMap; 19 | import java.util.List; 20 | import java.util.Map; 21 | 22 | import static com.github.yt.mybatis.mybatis.SqlBuilder.*; 23 | 24 | 25 | public class SearchProvider extends MapperProvider { 26 | 27 | public String findById(Map param) { 28 | begin(); 29 | Class entityClass = (Class) param.get(BaseMapper.ENTITY_CLASS); 30 | if (param.get(BaseMapper.ID) == null || StringUtils.isEmpty(param.get(BaseMapper.ID).toString())) { 31 | throw new BaseErrorException(StringUtils.join(entityClass.getName(), ",find单个对象时主键不能为空!")); 32 | } 33 | SELECT(JPAUtils.getSelectSql(entityClass)); 34 | FROM(getTableName(entityClass)); 35 | WHERE(getEqualsValue(JPAUtils.getAnnotationColumnName(JPAUtils.getIdField(entityClass)), BaseMapper.ID)); 36 | return sql(); 37 | } 38 | 39 | 40 | public String findAll(Map param) { 41 | begin(); 42 | QueryHandler queryHandler = (QueryHandler) param.get(BaseMapper.QUERY_HANDLER); 43 | ChainMap chainMap = BeanUtils.getValueMap(queryHandler, param.get(BaseMapper.ENTITY)) 44 | .chainPutAll(queryHandler == null ? null : queryHandler.getExpandData()); 45 | param.put(BaseMapper.DATA, chainMap); 46 | param.put(BaseMapper.ENTITY_CLASS, param.get(BaseMapper.ENTITY).getClass()); 47 | Class entityClass = param.get(BaseMapper.ENTITY).getClass(); 48 | Map map = ((Map) param.get(BaseMapper.DATA)); 49 | String selectColumnSql = createSelectColumnSql(entityClass, map); 50 | if (MapUtils.isNotEmpty(map) && map.containsKey("distinct")) { 51 | SELECT_DISTINCT(selectColumnSql); 52 | } else { 53 | SELECT(selectColumnSql); 54 | } 55 | FROM(getTableNameWithAlias(entityClass)); 56 | createAllWhere(entityClass, map, false); 57 | return StringUtils.join(sql(), createLimit(map)); 58 | } 59 | 60 | public String pageTotalRecord(Map param) { 61 | begin(); 62 | QueryHandler queryHandler = (QueryHandler) param.get(BaseMapper.QUERY_HANDLER); 63 | ChainMap chainMap = BeanUtils.getValueMap(queryHandler, param.get(BaseMapper.ENTITY)) 64 | .chainPutAll(queryHandler == null ? null : queryHandler.getExpandData()); 65 | param.put(BaseMapper.DATA, chainMap); 66 | param.put(BaseMapper.ENTITY_CLASS, param.get(BaseMapper.ENTITY).getClass()); 67 | Class entityClass = param.get(BaseMapper.ENTITY).getClass(); 68 | SELECT(createSelectCountColumnSql(param)); 69 | FROM(getTableNameWithAlias(entityClass)); 70 | createAllWhere(entityClass, (Map) param.get(BaseMapper.DATA), true); 71 | return sql(); 72 | } 73 | 74 | private void createAllWhere(Class entityClass, Map param, boolean isCount) { 75 | if (MapUtils.isEmpty(param)) { 76 | return; 77 | } 78 | try { 79 | for (Field field : JPAUtils.getAllFields(entityClass)) { 80 | createFieldWhereSql(field, param); 81 | } 82 | parseQueryHandle(param, isCount); 83 | } catch (Exception e) { 84 | throw new BaseErrorException(e); 85 | } 86 | } 87 | 88 | private boolean createFieldWhereSql(Field field, Map param) { 89 | if (!validateFieldWhereSql(field, param)) { 90 | return false; 91 | } 92 | if (null != field.getType().getAnnotation(Table.class)) { 93 | return false; 94 | } 95 | WHERE(StringUtils.join("t.", getEqualsValue(JPAUtils.getAnnotationColumnName(field), StringUtils.join(BaseMapper.DATA + ".", field.getName())))); 96 | return true; 97 | } 98 | 99 | private boolean validateFieldWhereSql(Field field, Map 100 | param) { 101 | if (null != field.getAnnotation(Transient.class) || field.getType().isAssignableFrom(Class.class)) { 102 | return false; 103 | } 104 | return param.containsKey(field.getName()); 105 | } 106 | 107 | private void parseQueryHandle(Map param, boolean isCount) { 108 | if (param.containsKey("orderBy") && !isCount) { 109 | LinkedHashMap orderByMap = (LinkedHashMap) param.get("orderBy"); 110 | for (String orderBy : orderByMap.keySet()) { 111 | if (orderBy.contains(".")) { 112 | ORDER_BY(orderBy + " " + orderByMap.get(orderBy)); 113 | continue; 114 | } 115 | ORDER_BY(StringUtils.join("t.", orderBy, " ", orderByMap.get(orderBy))); 116 | } 117 | } 118 | if (param.containsKey("whereSqls")) { 119 | List whereSqlList = (List) param.get("whereSqls"); 120 | for (String whereSql : whereSqlList) { 121 | WHERE(whereSql); 122 | } 123 | } 124 | if (param.containsKey("sqlJoinHandler")) { 125 | List sqlJoinHandles = (List) param.get("sqlJoinHandler"); 126 | for (SQLJoinHandler sqlJoin : sqlJoinHandles) { 127 | switch (sqlJoin.getJoinType()) { 128 | case JOIN: { 129 | JOIN(sqlJoin.getJoinSql()); 130 | if (StringUtils.isNotEmpty(sqlJoin.getSelectColumns()) && !isCount) { 131 | SELECT(sqlJoin.getSelectColumns()); 132 | } 133 | break; 134 | } 135 | case INNER_JOIN: { 136 | INNER_JOIN(sqlJoin.getJoinSql()); 137 | if (StringUtils.isNotEmpty(sqlJoin.getSelectColumns()) && !isCount) { 138 | SELECT(sqlJoin.getSelectColumns()); 139 | } 140 | break; 141 | } 142 | case LEFT_OUTER_JOIN: { 143 | LEFT_OUTER_JOIN(sqlJoin.getJoinSql()); 144 | if (StringUtils.isNotEmpty(sqlJoin.getSelectColumns()) && !isCount) { 145 | SELECT(sqlJoin.getSelectColumns()); 146 | } 147 | break; 148 | } 149 | case RIGHT_OUTER_JOIN: { 150 | RIGHT_OUTER_JOIN(sqlJoin.getJoinSql()); 151 | if (StringUtils.isNotEmpty(sqlJoin.getSelectColumns()) && !isCount) { 152 | SELECT(sqlJoin.getSelectColumns()); 153 | } 154 | break; 155 | } 156 | } 157 | } 158 | } 159 | } 160 | 161 | private String createLimit(Map param) { 162 | return !param.containsKey(BaseMapper.START) ? "" : StringUtils.join(" limit ", (Integer) param.get(BaseMapper.START), " , ", (Integer) param.get(BaseMapper.LIMIT)); 163 | } 164 | 165 | private String createSelectCountColumnSql(Map param) { 166 | Map map = ((Map) param.get(BaseMapper.DATA)); 167 | String selectColumnSql = "count(distinct t." + JPAUtils.getAnnotationColumnName(JPAUtils.getIdField((Class) param.get(BaseMapper.ENTITY_CLASS))) + ")"; 168 | if (map == null) { 169 | return selectColumnSql; 170 | } 171 | if (map.containsKey("selectColumnSql") && map.get("selectColumnSql") != null) { 172 | selectColumnSql = " count(distinct " + map.get("selectColumnSql").toString() + ") "; 173 | } 174 | return selectColumnSql; 175 | } 176 | 177 | private String createSelectColumnSql(Class entityClass, Map map) { 178 | String selectColumnSql = JPAUtils.getSelectSql(entityClass, "t."); 179 | if (MapUtils.isNotEmpty(map) && map.containsKey("selectColumnSql") && map.get("selectColumnSql") != null) { 180 | selectColumnSql = " " + map.get("selectColumnSql").toString() + " "; 181 | } 182 | return selectColumnSql; 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/generator/CreateBean.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.generator; 2 | 3 | import org.apache.commons.lang.StringUtils; 4 | 5 | import java.sql.*; 6 | import java.util.*; 7 | 8 | 9 | public class CreateBean { 10 | 11 | static String url; 12 | static String username; 13 | static String password; 14 | static String dbInstance; 15 | 16 | private static final List ingoreColumns = Arrays.asList("founderId", "founderName", "modifierId", 17 | "modifierName", "deleteFlag", "createDateTime", "modifyDateTime"); 18 | 19 | static { 20 | try { 21 | Class.forName("com.mysql.jdbc.Driver"); 22 | } catch (Exception e) { 23 | e.printStackTrace(); 24 | } 25 | } 26 | 27 | public void setMysqlInfo(String url, String username, String password, String dbInstance) { 28 | this.url = url; 29 | this.username = username; 30 | this.password = password; 31 | this.dbInstance = dbInstance; 32 | } 33 | 34 | public Connection getConnection() throws SQLException { 35 | System.out.println(url); 36 | return DriverManager.getConnection(url, username, password); 37 | } 38 | 39 | public List getColumnDatas(String tableName) throws SQLException { 40 | String SQLColumns = "SELECT distinct COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT,COLUMN_KEY,CHARACTER_MAXIMUM_LENGTH" + 41 | ",IS_NULLABLE,COLUMN_DEFAULT FROM information_schema.columns WHERE table_name = '" + tableName + "' " + "and table_schema='" + dbInstance + "' "; 42 | Connection con = this.getConnection(); 43 | PreparedStatement ps = con.prepareStatement(SQLColumns); 44 | List columnList = new ArrayList(); 45 | ResultSet rs = ps.executeQuery(); 46 | StringBuffer str = new StringBuffer(); 47 | StringBuffer getset = new StringBuffer(); 48 | while (rs.next()) { 49 | String name = rs.getString(1); 50 | String type = rs.getString(2); 51 | String comment = rs.getString(3); 52 | String priKey = rs.getString(4); 53 | Long length = rs.getLong(5); 54 | String isNullable = rs.getString(6); 55 | String columnDefault = rs.getString(7); 56 | type = this.getType(type); 57 | if (ingoreColumns.contains(name)) { 58 | continue; 59 | } 60 | ColumnData cd = new ColumnData(); 61 | cd.setColumnName(name); 62 | cd.setDataType(type); 63 | cd.setColumnComment(comment); 64 | cd.setColumnNameContainEntity("${entity." + name + " }"); 65 | cd.setIsPriKey("PRI".equals(priKey)); 66 | cd.setColumnLength(length); 67 | cd.setIsNullable("NO".equals(isNullable)); 68 | cd.setColumnDefault(columnDefault); 69 | columnList.add(cd); 70 | } 71 | argv = str.toString(); 72 | method = getset.toString(); 73 | rs.close(); 74 | ps.close(); 75 | con.close(); 76 | return columnList; 77 | } 78 | 79 | private String method; 80 | private String argv; 81 | 82 | 83 | public String getBeanFeilds(String tableName) throws SQLException { 84 | List dataList = getColumnDatas(tableName); 85 | StringBuffer str = new StringBuffer(); 86 | StringBuffer getset = new StringBuffer(); 87 | for (ColumnData d : dataList) { 88 | String name = getTablesColumnToAttributeName(d.getColumnName()); 89 | String type = d.getDataType(); 90 | String comment = d.getColumnComment(); 91 | Long length = d.getColumnLength(); 92 | Boolean isNullAble = d.getIsNullable(); 93 | String columnDefault = d.getColumnDefault(); 94 | // type=this.getType(type); 95 | String maxChar = name.substring(0, 1).toUpperCase(); 96 | str.append("\r\n\t/** \r\n\t * ").append(comment).append(" \r\n\t */"); 97 | if (d.getIsPriKey()) { 98 | str.append("\r\n\t@javax.persistence.Id"); 99 | } 100 | if (StringUtils.isEmpty(columnDefault) && isNullAble != null && !isNullAble) { 101 | str.append("\r\n\t@NotEmpty(message = \"" + name + "不能为空!\")"); 102 | } 103 | if (length != null && length > 0) { 104 | str.append("\r\n\t@Length(max = " + length + ", message = \"" + name + "长度不能超过" + length + "!\")"); 105 | } 106 | str.append("\r\n\t").append("private ").append(type + " ").append(name).append(";"); 107 | String method = maxChar + name.substring(1, name.length()); 108 | getset.append("\r\n\t\r\n\t").append("public ").append(type + " ").append("get" + method + "() {\r\n\t"); 109 | getset.append(" return this.").append(name).append(";\r\n\t}"); 110 | getset.append("\r\n\t\r\n\t").append("public ").append(getTablesNameToClassName(tableName)).append(" ") 111 | .append("set" + method + "(" + type + " " + name + ") {\r\n\t"); 112 | getset.append("\tthis.").append(name).append(" = ").append(name).append(";\r\n\t\treturn this;\r\n\t}"); 113 | } 114 | argv = str.toString(); 115 | method = getset.toString(); 116 | return argv + method; 117 | } 118 | 119 | public String getType(String type) { 120 | switch (type = type.toLowerCase()) { 121 | case "char": 122 | case "varchar": 123 | case "text": 124 | return "String"; 125 | case "int": 126 | return "Integer"; 127 | case "bigint": 128 | return "java.math.BigInteger"; 129 | case "decimal": 130 | return "java.math.BigDecimal"; 131 | case "timestamp": 132 | case "date": 133 | case "datetime": 134 | // return "java.sql.Timestamp"; 135 | return "java.util.Date"; 136 | case "float": 137 | return "Float"; 138 | case "double": 139 | return "Double"; 140 | case "tinyint": 141 | return "Boolean"; 142 | default: 143 | return null; 144 | } 145 | } 146 | 147 | public String getTablesNameToClassName(String tableName) { 148 | String[] split = tableName.split("_"); 149 | if (split.length > 1) { 150 | StringBuffer sb = new StringBuffer(); 151 | for (int i = 0; i < split.length; i++) { 152 | String tempTableName = split[i].substring(0, 1).toUpperCase() 153 | + split[i].substring(1).toLowerCase(); 154 | sb.append(tempTableName); 155 | } 156 | System.out.println(sb.toString()); 157 | return sb.toString(); 158 | } else { 159 | String tempTables = split[0].substring(0, 1).toUpperCase() + split[0].substring(1, split[0].length()); 160 | return tempTables; 161 | } 162 | } 163 | 164 | 165 | public String getTablesColumnToAttributeName(String columnName) { 166 | String[] split = columnName.split("_"); 167 | if (split.length > 1) { 168 | StringBuffer sb = new StringBuffer(); 169 | for (int i = 0; i < split.length; i++) { 170 | String tempTableName = ""; 171 | if (i == 0) { 172 | tempTableName = split[i].substring(0, 1).toLowerCase() + split[i].substring(1, split[i].length()); 173 | } else { 174 | tempTableName = split[i].substring(0, 1).toUpperCase() + split[i].substring(1, split[i].length()); 175 | } 176 | sb.append(tempTableName); 177 | } 178 | System.out.println(sb.toString()); 179 | return sb.toString(); 180 | } else { 181 | String tempTables = split[0].substring(0, 1).toLowerCase() + split[0].substring(1, split[0].length()); 182 | return tempTables; 183 | } 184 | } 185 | 186 | public Map getAutoCreateSql(String tableName) throws Exception { 187 | Map sqlMap = new HashMap(); 188 | List columnDatas = getColumnDatas(tableName); 189 | String columns = this.getColumnSplit(columnDatas); 190 | String[] columnList = getColumnList(columns); 191 | String columnFields = getColumnFields(columns); 192 | sqlMap.put("columnList", columnList); 193 | sqlMap.put("columnFields", columnFields); 194 | return sqlMap; 195 | } 196 | 197 | public String getColumnFields(String columns) throws SQLException { 198 | String fields = columns; 199 | if (fields != null && !"".equals(fields)) { 200 | fields = fields.replaceAll("[|]", ","); 201 | } 202 | return fields; 203 | } 204 | 205 | public String[] getColumnList(String columns) throws SQLException { 206 | String[] columnList = columns.split("[|]"); 207 | return columnList; 208 | } 209 | 210 | public String getColumnSplit(List columnList) throws SQLException { 211 | StringBuffer commonColumns = new StringBuffer(); 212 | for (ColumnData data : columnList) { 213 | commonColumns.append(data.getColumnName() + "|"); 214 | } 215 | return commonColumns.delete(commonColumns.length() - 1, commonColumns.length()).toString(); 216 | } 217 | 218 | } 219 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # yt_mybatis 2 | 3 |
4 | 欢迎加入QQ群~ 489333310~,我们一起进步,不限于mybatis。 5 |
6 |

介绍

7 | yt_mybatis是基于mybaits封装的CURD项目;也同时提供了从web端请求到数据库,再返回给前端的一整套解决方案
8 | 9 | 当然您可以仅使用yt_mybatis的CURD部分。如果您是新项目,欢迎您使用整体解决方案;如果您是历史项目,您可以很快集成CURD。
10 | 11 | 您可以下载https://github.com/limiaogithub/yt_mybatis_example 直接运行示例代码。
12 | 您还可以下载https://github.com/limiaogithub/yt_antd_pro 结合前后端一起运行查看增删改查效果,这是目前最新的基于react的ant design技术,前后端分离最佳实践
13 | 14 |

为什么使用yt_mybatis

15 | yt_mybatis的意义在于增加了一些编码约定,比如创建人、创建时间、修改人、修改时间等字段,一般的业务系统表中都应该存储,为了防止设计缺陷,架构师可以使用yt_mybatis强行约定继承框架的实体类,具体的值会默认注入。
16 | yt_mybatis还在持续维护中,目的在于让开发人员效率提升三倍,代码更加简洁、异常等控制更加完善。
17 | 18 |

特性

19 | 1.免费开源
20 | 2.一键接入增删改查
21 | 3.不仅支持CURD单表操作,还支持级联join多表查询
22 | 4.支持domain默认值自动注入,可以自定义注入值
23 | 5.支持limit分页,可以重写获取前台请求limit,offset方法
24 | 6.支持spring-boot
25 | 7.提供BaseAccidentException和BaseErrorException
26 | 8.提供全新代码生成器
27 | 9.提供example工程,一键测试运行
28 | 10.new~ 支持domain自定义映射数据库字段名称
29 |
 30 | @Column(name="member_name")
 31 | private String memberName;
 32 | 
33 |

准备

34 | 1.mysql数据库
35 | 2.idea开发工具
36 | 3.大约10分钟
37 | 38 |

集成

39 |

a.简单CURD的集成(仅需两步)


40 | 1.引入maven依赖
41 |
 42 | <dependency>
 43 |     <groupId>com.github.limiaogithub</groupId>
 44 |     <artifactId>yt_mybatis</artifactId>
 45 |     <version>3.0.1</version>
 46 | </dependency>
 47 | 
48 | 2.你的mapper继承BaseMapper
49 | 这里的泛型是你的domain
50 |
 51 | public interface TestMapper extends BaseMapper<MemberT> {
 52 | 
53 | } 54 |
55 | 3.配置完毕,现在你可以使用TestMapper进行curd操作,示例如下
56 |
 57 | @Service
 58 | public class TestServiceImpl implements TestService {
 59 | 
 60 |     @Resource
 61 |     private TestMapper testMapper;
 62 | 
 63 |     @Override
 64 |     public void test() {
 65 | 
 66 |         //测试save
 67 |         MemberT member = new MemberT().setUserName("测试name2").setPhone("18888888888").setAge(30);
 68 |         testMapper.save(member);
 69 | 
 70 |         //测试update
 71 |         member.setUserName("修改名称");
 72 |         testMapper.updateForSelective(member);
 73 | 
 74 |         //测试findById
 75 |         member = testMapper.find(MemberT.class, member.getMemberId());
 76 | 
 77 |         //测试findAll
 78 |         QueryHandler queryHandler = new QueryHandler();
 79 |         List queryList = new ArrayList<>();
 80 |         queryList.add("18888888888");
 81 |         queryList.add("18888888889");
 82 |         queryHandler.addWhereSql("t.age=#{data.age1} and t.phone in" + QueryHandler.getInSql("data.phone1", queryList.size()));
 83 |         queryHandler.addExpandData("age1", 30);
 84 |         queryHandler.addExpandData("phone1", queryList.toArray());
 85 |         List list = testMapper.findAll(new MemberT(), queryHandler);
 86 | 
 87 |         //测试分页查询
 88 |         MemberT memberT = new MemberT();
 89 |         memberT.setPhone("18888888888");
 90 |         List list1 = testMapper.findAll(memberT, queryHandler.configPage().setStart(0).setLimit(10));
 91 |         Long total = testMapper.pageTotalRecord(memberT, queryHandler);
 92 |         System.out.println(total);
 93 | 
 94 |         //测试逻辑删除(需要你的domain继承BaseEntity)
 95 |         testMapper.logicDelete(MemberT.class, member.getMemberId());
 96 | 
 97 |         //测试delete
 98 |         testMapper.delete(MemberT.class, member.getMemberId());
 99 | 
100 |         //测试级联查询,不建议复杂场景使用,不宜维护
101 |         QueryHandler queryHandler2 = new QueryHandler();
102 |         //queryHandler.configPage();
103 |         List list2 = testMapper.findAll(new MemberT(), queryHandler2.addJoinHandle("cardt.*", SQLJoinHandler.JoinType.LEFT_OUTER_JOIN, "cardt cardt on t.memberId=cardt.memberId"));
104 |         System.out.println(list2.size());
105 |     }
106 | }
107 | 
108 | 输出结果: 109 |
110 |  ==>  Preparing: INSERT INTO MemberT (userName, age, phone, memberId) VALUES (?, ?, ?, 'b9d8cbd6664640b18eab932d88379b2d') 
111 |  ==> Parameters: 测试name2(String), 30(Integer), 18888888888(String)
112 |  <==    Updates: 1
113 |  ==>  Preparing: UPDATE MemberT SET userName = ?, age = ?, phone = ? WHERE (memberId = ?) 
114 |  ==> Parameters: 修改名称(String), 30(Integer), 18888888888(String), b9d8cbd6664640b18eab932d88379b2d(String)
115 |  <==    Updates: 1
116 |  ==>  Preparing: SELECT * FROM MemberT WHERE (memberId = ?) 
117 |  ==> Parameters: b9d8cbd6664640b18eab932d88379b2d(String)
118 |  <==      Total: 1
119 |  ==>  Preparing: SELECT t.* FROM MemberT t WHERE (t.age=? and t.phone in(?,?)) 
120 |  ==> Parameters: 30(Integer), 18888888888(String), 18888888889(String)
121 |  <==      Total: 1
122 |  ==>  Preparing: SELECT t.* FROM MemberT t WHERE (t.phone = ? AND t.age=? and t.phone in(?,?)) limit 0 , 10 
123 |  ==> Parameters: 18888888888(String), 30(Integer), 18888888888(String), 18888888889(String)
124 |  <==      Total: 1
125 |  ==>  Preparing: SELECT count(distinct t.memberId) FROM MemberT t WHERE (t.phone = ? AND t.age=? and t.phone in(?,?)) 
126 |  ==> Parameters: 18888888888(String), 30(Integer), 18888888888(String), 18888888889(String)
127 |  <==      Total: 1
128 | 
129 |  ==>  Preparing: UPDATE MemberT SET deleteFlag=1 WHERE (memberId = ?) 
130 |  ==> Parameters: b9d8cbd6664640b18eab932d88379b2d(String)
131 |  <==    Updates: 1
132 |  ==>  Preparing: DELETE FROM MemberT WHERE (memberId = ?) 
133 |  ==> Parameters: b9d8cbd6664640b18eab932d88379b2d(String)
134 |  <==    Updates: 1
135 |  ==>  Preparing: SELECT t.* , cardt.* FROM MemberT t LEFT OUTER JOIN cardt cardt on t.memberId=cardt.memberId 
136 |  ==>  Parameters: 
137 |  <==      Total: 2
138 | 
139 | 140 | 141 |

b.整体解决方案的集成


142 | 一般的j2ee后台结构包括controller、service、serviceImpl、mapper、domain,本文按照这种结构提供示例。
143 | 本文domain以MemberT作为示例
144 | 145 | 1.引入maven依赖
146 |
147 | <dependency>
148 |     <groupId>com.github.limiaogithub</groupId>
149 |     <artifactId>yt_mybatis</artifactId>
150 |     <version>3.0.1</version>
151 | </dependency>
152 | 
153 | 2.你的mapper继承BaseMapper
154 |
155 | public interface TestMapper extends BaseMapper<MemberT> {
156 | 
157 | } 158 |
159 | 3.你的service继承BaseService<T>,
160 |
161 | public interface TestService extends BaseService<MemberT>{
162 | 
163 | } 164 |
165 | 166 | 4.你的serviceImpl继承ServiceSupport<T, yourMapper>,这里需要实现getMapper()方法
167 |
168 | @Service
169 | public class TestServiceImpl extends ServiceSupport<MemberT, TestMapper> implements TestService {
170 | 
171 |     @Resource
172 |     private TestMapper testMapper;
173 | 
174 | 
175 |     @Override
176 |     public TestMapper getMapper() {
177 |         return testMapper;
178 |     }
179 | }
180 | 
181 | 5.你的controller集成BaseController
182 |
183 | public class MemberController extends BaseController
184 | 
185 | 186 | 6.配置完毕,现在你可以体验从请求到返回的所有操作!
187 | 代码较多,请访问https://github.com/limiaogithub/yt_mybatis_example 直接运行示例代码。 188 | 189 | 190 |

代码生成器

191 | 1.请先在数据库中创建表,yt_mybatis推荐您每张表都包含如下字段,您只需要继承BaseEntity对象即可。 192 |
193 | `founderId` varchar(36) DEFAULT '' COMMENT '创建人ID',
194 | `founderName` varchar(30) DEFAULT '' COMMENT '创建人姓名',
195 | `modifierId` varchar(36) DEFAULT '' COMMENT '修改人ID',
196 | `modifierName` varchar(30) DEFAULT '' COMMENT '修改人姓名',
197 | `createDateTime` datetime NOT NULL DEFAULT '1000-01-01 00:00:00' COMMENT '创建时间',
198 | `modifyDateTime` datetime NOT NULL DEFAULT '1000-01-01 00:00:00' COMMENT '修改时间',
199 | `deleteFlag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否删除 0 否 1是'
200 | 
201 | 202 | 203 | 2.新建JavaBuild类,代码示例如下,运行test()方法即可,代码会直接生成在modulePackage配置目录下
204 | 205 |
206 | import com.github.yt.generator.JavaCodeGenerator;
207 | 
208 | public class JavaBuild {
209 | 
210 |     @org.testng.annotations.Test
211 |     public void test() {
212 | 
213 |         JavaCodeGenerator generator = new JavaCodeGenerator(
214 |                 "root",
215 |                 "1234",
216 |                 "antdpro",
217 |                 "jdbc:mysql://localhost:3307/antdpro");
218 | 
219 |         String tableName = "OrderT";
220 |         String codeName = "订单";
221 |         String moduleName = "订单";
222 |         String modulePackage = "com.github.yt.example.order";
223 |         generator.create(tableName, codeName, moduleName, modulePackage
224 |                 //  , "html"
225 |                 , "bean"
226 |                 , "controller"
227 |                 , "service"
228 |                 , "mapper"
229 |                 , "mapper_xml"
230 |         );
231 |     }
232 | 
233 | }
234 | 
235 | 236 | 237 |

其他配置

238 | 1.自定义字段注入来源
239 | 创建MyFieldsConfig类,实现FieldsDefault接口,指定service名字为"ytFieldsConfig"。 240 |
241 | @Service("ytFieldsConfig")
242 | public class MyFieldsConfig implements FieldsDefault {
243 | 
244 | 
245 |     @Override
246 |     public String getOperator() {
247 |         return (String) getSessionAttr("Operator");
248 |     }
249 | 
250 |     @Override
251 |     public String getOperatorId() {
252 |         return (String) getSessionAttr("OperatorId");
253 |     }
254 | 
255 |     @Override
256 |     public String getModifyOperator() {
257 |         return (String) getSessionAttr("Operator");
258 |     }
259 | 
260 |     @Override
261 |     public String getModifyOperatorId() {
262 |         return (String) getSessionAttr("OperatorId");
263 |     }
264 | 
265 |     private Object getSessionAttr(String attr) {
266 |         return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession()
267 |                 .getAttribute(attr);
268 |     }
269 | 
270 | }
271 | 
272 | 273 | 2.自定义分页处理类
274 | 创建MyPageConfig类,实现PageConvert接口,指定service名字为"ytPageConfig"。 275 |
276 | @Service("ytPageConfig")
277 | //这里的目的是设置queryHandler中的start(从第几条读)和 limit(读取多少条);如果不设置这个service,将默认读取CommonPageService中的配置
278 | public class MyPageConfig implements PageConvert {
279 | 
280 |     @Override
281 |     public void convert(QueryHandler queryHandler, HttpServletRequest request) {
282 |         queryHandler.setStart(0);
283 |         queryHandler.setLimit(20);
284 |     }
285 | }
286 | 
287 | 288 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/generator/JavaCodeGenerator.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.generator; 2 | 3 | 4 | import org.apache.commons.lang3.ArrayUtils; 5 | import org.apache.commons.lang3.StringUtils; 6 | import org.apache.velocity.VelocityContext; 7 | 8 | import java.io.File; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | 14 | public class JavaCodeGenerator { 15 | 16 | private static final String BEAN = "bean"; 17 | private static final String MAPPER = "mapper"; 18 | private static final String MAPPER_XML = "mapper_xml"; 19 | private static final String SERVICE = "service"; 20 | private static final String CONTROLLER = "controller"; 21 | private static final String HTML = "html"; 22 | 23 | private String username; 24 | private String passWord; 25 | private String dbInstance; 26 | private String url; 27 | 28 | public JavaCodeGenerator(String username, String passWord, String dbInstance, String url) { 29 | this.username = username; 30 | this.passWord = passWord; 31 | this.dbInstance = dbInstance; 32 | this.url = url; 33 | } 34 | 35 | private static List CLASS_NAME_SUFFIX_LIST = new ArrayList<>(); 36 | 37 | static { 38 | CLASS_NAME_SUFFIX_LIST.add("T"); 39 | CLASS_NAME_SUFFIX_LIST.add("R"); 40 | } 41 | 42 | public String getReplaceSuffixClassName(String className) { 43 | if (className == null || className.length() < 1) { 44 | return className; 45 | } 46 | String suffix = className.substring(className.length() - 1, className.length()); 47 | if (CLASS_NAME_SUFFIX_LIST.contains(suffix)) { 48 | className = className.substring(0, className.length() - 1); 49 | } 50 | return className; 51 | } 52 | 53 | /** 54 | * @param tableName 表名 55 | * @param codeName 表名对应的中文注释 56 | * @param modulePackage 模块包:com.fdcz.pro.system 57 | * @param moduleName 模块名 58 | * @param templates 生成那些模板 59 | */ 60 | public void create(String tableName, String codeName, String moduleName, String modulePackage, String... templates) { 61 | if (null == tableName || "".equals(tableName)) { 62 | return; 63 | } 64 | if (null == codeName || "".equals(codeName)) { 65 | return; 66 | } 67 | if (null == modulePackage || "".equals(modulePackage)) { 68 | return; 69 | } 70 | 71 | CreateBean createBean = new CreateBean(); 72 | createBean.setMysqlInfo(url, username, passWord, dbInstance); 73 | String className = createBean.getTablesNameToClassName(tableName); 74 | String replaceSuffixClassName = getReplaceSuffixClassName(className); 75 | String lowerName = className.substring(0, 1).toLowerCase() + className.substring(1, className.length()); 76 | String replaceSuffixLowerName = replaceSuffixClassName.substring(0, 1).toLowerCase() + replaceSuffixClassName.substring(1, replaceSuffixClassName.length()); 77 | String rootPath = CommonPageParser.getRootPath(); 78 | String resourcePath = File.separator + "src" + File.separator + "main" + File.separator 79 | + "resources" + File.separator; 80 | String javaPath = File.separator + "src" + File.separator + "main" + File.separator + "java" 81 | + File.separator; 82 | String webappPath = File.separator + "src" + File.separator + "main" + File.separator + "webapp" 83 | + File.separator + "module" + File.separator; 84 | String moduleSimplePackage = modulePackage 85 | .substring(modulePackage.lastIndexOf(".") + 1, modulePackage.length()); 86 | 87 | // //根路径 88 | // String srcPath = rootPath + "src" + File.separator + "main" + File.separator + "java"; 89 | // //包路径 90 | // String pckPath = rootPath + "com" + File.separator + "fdcz" + File.separator + "pro" + File.separator + 91 | // "system"; 92 | // 93 | // File file=new File(pckPath); 94 | // java,xml文件名称 95 | String modelPath = File.separator + "domain" + File.separator + className + ".java"; 96 | String searchFormPath = File.separator + "controller" + File.separator + "form" + File.separator + className 97 | + "SearchForm.java"; 98 | 99 | //String mapperPath = File.separator + "dao" + File.separator + className + "Mapper.java"; 100 | String mapperPath = File.separator + "dao" + File.separator + replaceSuffixClassName + "Mapper.java"; 101 | 102 | //String mapperXmlPath = File.separator + "dao" + File.separator + className + "Mapper.xml"; 103 | String mapperXmlPath = File.separator + "dao" + File.separator + replaceSuffixClassName + "Mapper.xml"; 104 | 105 | //String servicePath = File.separator + "service" + File.separator + className + "Service.java"; 106 | String servicePath = File.separator + "service" + File.separator + replaceSuffixClassName + "Service.java"; 107 | 108 | //String serviceImplPath = File.separator + "service" + File.separator + "impl" + File.separator + className 109 | // + "ServiceImpl.java"; 110 | String serviceImplPath = File.separator + "service" + File.separator + "impl" + File.separator + replaceSuffixClassName 111 | + "ServiceImpl.java"; 112 | //String controllerPath = File.separator + "controller" + File.separator + className + "Controller.java"; 113 | String controllerPath = File.separator + "controller" + File.separator + replaceSuffixClassName + "Controller.java"; 114 | 115 | //String sqlMapperPath = File.separator + "dao" + File.separator + className + "Mapper.xml"; 116 | String sqlMapperPath = File.separator + "dao" + File.separator + replaceSuffixClassName + "Mapper.xml"; 117 | 118 | //String htmlPath = File.separator + className + ".html"; 119 | String htmlPath = File.separator + replaceSuffixLowerName + ".html"; 120 | 121 | //String listJSPPath = lowerName + File.separator + className + "List.jsp"; 122 | String listJSPPath = lowerName + File.separator + replaceSuffixLowerName + "List.jsp"; 123 | 124 | // String editJSPPath = lowerName + File.separator + "edit" + className + ".jsp"; 125 | String editJSPPath = lowerName + File.separator + "edit" + replaceSuffixLowerName + ".jsp"; 126 | 127 | // String springPath="conf" + File.separator + "spring" + File.separator ; 128 | // String sqlMapPath="conf" + File.separator + "mybatis" + File.separator ; 129 | 130 | VelocityContext context = new VelocityContext(); 131 | context.put("className", className); 132 | context.put("lowerName", lowerName); 133 | context.put("codeName", codeName); 134 | context.put("moduleName", moduleName); 135 | context.put("tableName", tableName); 136 | context.put("modulePackage", modulePackage); 137 | context.put("importPackage", modulePackage); 138 | context.put("moduleSimplePackage", moduleSimplePackage); 139 | context.put("replaceSuffixClassName", replaceSuffixClassName); 140 | context.put("replaceSuffixLowerName", replaceSuffixLowerName); 141 | /****************************** 生成bean字段 *********************************/ 142 | try { 143 | context.put("feilds", createBean.getBeanFeilds(tableName)); // 生成bean 144 | } catch (Exception e) { 145 | e.printStackTrace(); 146 | } 147 | 148 | /******************************* 生成sql语句 **********************************/ 149 | try { 150 | Map sqlMap = createBean.getAutoCreateSql(tableName); 151 | List columnDatas = createBean.getColumnDatas(tableName); 152 | List normalColumns = new ArrayList<>(); 153 | ColumnData columnDataPriKey = new ColumnData(); 154 | for (ColumnData columnData : columnDatas) { 155 | if (columnData.getIsPriKey()) { 156 | columnDataPriKey = columnData; 157 | continue; 158 | } 159 | normalColumns.add(columnData); 160 | } 161 | context.put("columnDatas", columnDatas); // 生成bean 162 | context.put("prikey", columnDataPriKey.getColumnName()); // 生成主见 163 | context.put("normalColumns", normalColumns); // 生成非主键列表 164 | context.put("SQL", sqlMap); 165 | } catch (Exception e) { 166 | e.printStackTrace(); 167 | return; 168 | } 169 | 170 | // -------------------生成文件代码---------------------/ 171 | String realPath = rootPath; 172 | String modulePakPath = modulePackage.replaceAll("\\.", "/"); 173 | // 生成Model 174 | if (ArrayUtils.isNotEmpty(templates) && ArrayUtils.contains(templates, BEAN)) { 175 | CommonPageParser.WriterPage(context, "Bean.java.vm", realPath + javaPath + modulePakPath, modelPath); // 176 | } 177 | 178 | if (ArrayUtils.isNotEmpty(templates) && ArrayUtils.contains(templates, MAPPER)) { 179 | CommonPageParser.WriterPage(context, "Mapper.java.vm", realPath + javaPath + modulePakPath, mapperPath); // 生成MybatisMapper接口 180 | } 181 | 182 | if (ArrayUtils.isNotEmpty(templates) && ArrayUtils.contains(templates, MAPPER_XML)) {//生成xml 183 | CommonPageParser.WriterPage(context, "Mapper.xml.vm", realPath + resourcePath + modulePakPath, mapperXmlPath); // 184 | // 生成MybatisMapper接口 185 | } 186 | if (ArrayUtils.isNotEmpty(templates) && ArrayUtils.contains(templates, SERVICE)) { 187 | CommonPageParser.WriterPage(context, "Service.java.vm", realPath + javaPath + modulePakPath, servicePath);// 生成Service 188 | CommonPageParser.WriterPage(context, "ServiceImpl.java.vm", realPath + javaPath + modulePakPath, serviceImplPath);// 生成Service 189 | } 190 | 191 | // 配置controller 192 | if (ArrayUtils.isNotEmpty(templates) && ArrayUtils.contains(templates, CONTROLLER)) { 193 | CommonPageParser.WriterPage(context, "Controller.java.vm", rootPath + javaPath + modulePakPath, controllerPath);// 生成Controller 194 | } 195 | // 配置html 196 | if (ArrayUtils.isNotEmpty(templates) && ArrayUtils.contains(templates, HTML)) { 197 | CommonPageParser.WriterPage(context, "Html.html.vm", rootPath + webappPath + StringUtils.substringAfterLast 198 | (modulePackage, "."), htmlPath);// 199 | // 生成Controller 200 | } 201 | } 202 | 203 | 204 | public String getUsername() { 205 | return username; 206 | } 207 | 208 | public void setUsername(String username) { 209 | this.username = username; 210 | } 211 | 212 | public String getPassWord() { 213 | return passWord; 214 | } 215 | 216 | public void setPassWord(String passWord) { 217 | this.passWord = passWord; 218 | } 219 | 220 | public String getDbInstance() { 221 | return dbInstance; 222 | } 223 | 224 | public void setDbInstance(String dbInstance) { 225 | this.dbInstance = dbInstance; 226 | } 227 | 228 | public String getUrl() { 229 | return url; 230 | } 231 | 232 | public void setUrl(String url) { 233 | this.url = url; 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/main/java/com/github/yt/mybatis/mybatis/SQL.java: -------------------------------------------------------------------------------- 1 | package com.github.yt.mybatis.mybatis; 2 | 3 | import com.github.yt.mybatis.handler.SQLJoinHandler; 4 | import org.apache.commons.lang3.StringUtils; 5 | import org.apache.ibatis.jdbc.AbstractSQL; 6 | 7 | import java.io.IOException; 8 | import java.util.ArrayList; 9 | import java.util.Arrays; 10 | import java.util.List; 11 | 12 | 13 | public class SQL extends AbstractSQL { 14 | 15 | private static final String AND = ") \nAND ("; 16 | private static final String OR = ") \nOR ("; 17 | 18 | 19 | @Override 20 | public SQL getSelf() { 21 | return this; 22 | } 23 | 24 | public SQL UPDATE(String table) { 25 | sql().statementType = SQLStatement.StatementType.UPDATE; 26 | sql().tables.add(table); 27 | return getSelf(); 28 | } 29 | 30 | public SQL SET(String sets) { 31 | sql().sets.add(sets); 32 | return getSelf(); 33 | } 34 | 35 | public SQL INSERT_INTO(String tableName) { 36 | sql().statementType = SQLStatement.StatementType.INSERT; 37 | sql().tables.add(tableName); 38 | return getSelf(); 39 | } 40 | 41 | public SQL BATCH_INSERT_INTO(String tableName) { 42 | sql().statementType = SQLStatement.StatementType.BATCH_INSERT; 43 | sql().tables.add(tableName); 44 | return getSelf(); 45 | } 46 | 47 | public SQL BATCH_SEGMENTATION() { 48 | sql().columns.clear(); 49 | sql().columns.addAll(sql().batchColumns); 50 | sql().batchColumns.clear(); 51 | sql().values.add(StringUtils.join("(", StringUtils.join(sql().batchValues.toArray(), ","), ")")); 52 | sql().batchValues.clear(); 53 | return getSelf(); 54 | } 55 | 56 | public SQL VALUES(String columns, String values) { 57 | sql().columns.add(columns); 58 | sql().values.add(values); 59 | return getSelf(); 60 | } 61 | 62 | public SQL BATCH_VALUES(String columns, String values) { 63 | sql().batchColumns.add(columns); 64 | sql().batchValues.add(values); 65 | return getSelf(); 66 | } 67 | 68 | public SQL SELECT(String columns) { 69 | sql().statementType = SQLStatement.StatementType.SELECT; 70 | sql().select.add(columns); 71 | return getSelf(); 72 | } 73 | 74 | public SQL SELECT_DISTINCT(String columns) { 75 | sql().distinct = true; 76 | SELECT(columns); 77 | return getSelf(); 78 | } 79 | 80 | public SQL DELETE_FROM(String table) { 81 | sql().statementType = SQLStatement.StatementType.DELETE; 82 | sql().tables.add(table); 83 | return getSelf(); 84 | } 85 | 86 | public SQL FROM(String table) { 87 | sql().tables.add(table); 88 | return getSelf(); 89 | } 90 | 91 | public SQL JOIN(String join) { 92 | sql().sqlJoins.add(new SQLJoinHandler(SQLJoinHandler.JoinType.JOIN, join)); 93 | // sql().join.add(join); 94 | return getSelf(); 95 | } 96 | 97 | public SQL INNER_JOIN(String join) { 98 | sql().sqlJoins.add(new SQLJoinHandler(SQLJoinHandler.JoinType.INNER_JOIN, join)); 99 | // sql().innerJoin.add(join); 100 | return getSelf(); 101 | } 102 | 103 | public SQL LEFT_OUTER_JOIN(String join) { 104 | sql().sqlJoins.add(new SQLJoinHandler(SQLJoinHandler.JoinType.LEFT_OUTER_JOIN, join)); 105 | // sql().leftOuterJoin.add(join); 106 | return getSelf(); 107 | } 108 | 109 | public SQL RIGHT_OUTER_JOIN(String join) { 110 | sql().sqlJoins.add(new SQLJoinHandler(SQLJoinHandler.JoinType.RIGHT_OUTER_JOIN, join)); 111 | // sql().rightOuterJoin.add(join); 112 | return getSelf(); 113 | } 114 | 115 | public SQL OUTER_JOIN(String join) { 116 | sql().sqlJoins.add(new SQLJoinHandler(SQLJoinHandler.JoinType.OUTER_JOIN, join)); 117 | // sql().outerJoin.add(join); 118 | return getSelf(); 119 | } 120 | 121 | public SQL WHERE(String conditions) { 122 | sql().where.add(conditions); 123 | sql().lastList = sql().where; 124 | return getSelf(); 125 | } 126 | 127 | public SQL OR() { 128 | sql().lastList.add(OR); 129 | return getSelf(); 130 | } 131 | 132 | public SQL AND() { 133 | sql().lastList.add(AND); 134 | return getSelf(); 135 | } 136 | 137 | public SQL GROUP_BY(String columns) { 138 | sql().groupBy.add(columns); 139 | return getSelf(); 140 | } 141 | 142 | public SQL HAVING(String conditions) { 143 | sql().having.add(conditions); 144 | sql().lastList = sql().having; 145 | return getSelf(); 146 | } 147 | 148 | public SQL ORDER_BY(String columns) { 149 | sql().orderBy.add(columns); 150 | return getSelf(); 151 | } 152 | 153 | private SQLStatement sql = new SQLStatement(); 154 | 155 | private SQLStatement sql() { 156 | return sql; 157 | } 158 | 159 | public A usingAppender(A a) { 160 | sql().sql(a); 161 | return a; 162 | } 163 | 164 | @Override 165 | public String toString() { 166 | StringBuilder sb = new StringBuilder(); 167 | sql().sql(sb); 168 | return sb.toString(); 169 | } 170 | 171 | private static class SafeAppendable { 172 | private final Appendable a; 173 | private boolean empty = true; 174 | 175 | public SafeAppendable(Appendable a) { 176 | super(); 177 | this.a = a; 178 | } 179 | 180 | public SafeAppendable append(CharSequence s) { 181 | try { 182 | if (empty && s.length() > 0) empty = false; 183 | a.append(s); 184 | } catch (IOException e) { 185 | throw new RuntimeException(e); 186 | } 187 | return this; 188 | } 189 | 190 | public boolean isEmpty() { 191 | return empty; 192 | } 193 | 194 | } 195 | 196 | private static class SQLStatement { 197 | 198 | public enum StatementType { 199 | DELETE, INSERT, SELECT, UPDATE, BATCH_INSERT 200 | } 201 | 202 | StatementType statementType; 203 | List sets = new ArrayList(); 204 | List select = new ArrayList(); 205 | List tables = new ArrayList(); 206 | List sqlJoins = new ArrayList(); 207 | List join = new ArrayList(); 208 | List innerJoin = new ArrayList(); 209 | List outerJoin = new ArrayList(); 210 | List leftOuterJoin = new ArrayList(); 211 | List rightOuterJoin = new ArrayList(); 212 | List where = new ArrayList(); 213 | List having = new ArrayList(); 214 | List groupBy = new ArrayList(); 215 | List orderBy = new ArrayList(); 216 | List lastList = new ArrayList(); 217 | List columns = new ArrayList(); 218 | List values = new ArrayList(); 219 | List batchValues = new ArrayList<>(); 220 | List batchColumns = new ArrayList<>(); 221 | boolean distinct; 222 | 223 | private void sqlClause(SafeAppendable builder, String keyword, List parts, String open, String close, 224 | String conjunction) { 225 | if (!parts.isEmpty()) { 226 | if (!builder.isEmpty()) 227 | builder.append("\n"); 228 | builder.append(keyword); 229 | builder.append(" "); 230 | builder.append(open); 231 | String last = "________"; 232 | for (int i = 0, n = parts.size(); i < n; i++) { 233 | String part = parts.get(i); 234 | if (i > 0 && !part.equals(AND) && !part.equals(OR) && !last.equals(AND) && !last.equals(OR)) { 235 | builder.append(conjunction); 236 | } 237 | builder.append(part); 238 | last = part; 239 | } 240 | builder.append(close); 241 | } 242 | } 243 | 244 | private String selectSQL(SafeAppendable builder) { 245 | if (distinct) { 246 | sqlClause(builder, "SELECT DISTINCT", select, "", "", ", "); 247 | } else { 248 | sqlClause(builder, "SELECT", select, "", "", ", "); 249 | } 250 | sqlClause(builder, "FROM", tables, "", "", ", "); 251 | for (SQLJoinHandler sqlJoin : sqlJoins) { 252 | switch (sqlJoin.getJoinType()) { 253 | case JOIN: { 254 | sqlClause(builder, "JOIN", Arrays.asList(sqlJoin.getJoinSql()), "", "", "\nJOIN "); 255 | break; 256 | } 257 | case INNER_JOIN: { 258 | sqlClause(builder, "INNER JOIN", Arrays.asList(sqlJoin.getJoinSql()), "", "", "\nINNER JOIN "); 259 | break; 260 | } 261 | case LEFT_OUTER_JOIN: { 262 | sqlClause(builder, "LEFT OUTER JOIN", Arrays.asList(sqlJoin.getJoinSql()), "", "", "\nLEFT OUTER JOIN "); 263 | break; 264 | } 265 | case RIGHT_OUTER_JOIN: { 266 | sqlClause(builder, "RIGHT OUTER JOIN", Arrays.asList(sqlJoin.getJoinSql()), "", "", "\nRIGHT OUTER JOIN "); 267 | break; 268 | } 269 | case OUTER_JOIN: { 270 | sqlClause(builder, "OUTER JOIN", Arrays.asList(sqlJoin.getJoinSql()), "", "", "\nOUTER JOIN "); 271 | break; 272 | } 273 | 274 | } 275 | } 276 | sqlClause(builder, "WHERE", where, "(", ")", " AND "); 277 | sqlClause(builder, "GROUP BY", groupBy, "", "", ", "); 278 | sqlClause(builder, "HAVING", having, "(", ")", " AND "); 279 | sqlClause(builder, "ORDER BY", orderBy, "", "", ", "); 280 | return builder.toString(); 281 | } 282 | 283 | private String insertSQL(SafeAppendable builder) { 284 | sqlClause(builder, "INSERT INTO", tables, "", "", ""); 285 | sqlClause(builder, "", columns, "(", ")", ", "); 286 | sqlClause(builder, "VALUES", values, "(", ")", ", "); 287 | return builder.toString(); 288 | } 289 | 290 | private String batchInsertSQL(SafeAppendable builder) { 291 | sqlClause(builder, "INSERT INTO", tables, "", "", ""); 292 | sqlClause(builder, "", columns, "(", ")", ", "); 293 | sqlClause(builder, "VALUES", values, "", "", ", "); 294 | return builder.toString(); 295 | } 296 | 297 | private String deleteSQL(SafeAppendable builder) { 298 | sqlClause(builder, "DELETE FROM", tables, "", "", ""); 299 | sqlClause(builder, "WHERE", where, "(", ")", " AND "); 300 | return builder.toString(); 301 | } 302 | 303 | private String updateSQL(SafeAppendable builder) { 304 | sqlClause(builder, "UPDATE", tables, "", "", ""); 305 | sqlClause(builder, "SET", sets, "", "", ", "); 306 | sqlClause(builder, "WHERE", where, "(", ")", " AND "); 307 | return builder.toString(); 308 | } 309 | 310 | public String sql(Appendable a) { 311 | SafeAppendable builder = new SafeAppendable(a); 312 | if (statementType == null) { 313 | return null; 314 | } 315 | String answer; 316 | switch (statementType) { 317 | case DELETE: 318 | answer = deleteSQL(builder); 319 | break; 320 | case INSERT: 321 | answer = insertSQL(builder); 322 | break; 323 | case BATCH_INSERT: 324 | answer = batchInsertSQL(builder); 325 | break; 326 | case SELECT: 327 | answer = selectSQL(builder); 328 | break; 329 | case UPDATE: 330 | answer = updateSQL(builder); 331 | break; 332 | default: 333 | answer = null; 334 | } 335 | return answer; 336 | } 337 | } 338 | } --------------------------------------------------------------------------------