提交 707c8c1d 编写于 作者: M MaxKey

代码优化

上级 3436bf36
......@@ -21,6 +21,8 @@ import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.dromara.mybatis.jpa.entity.JpaEntity;
import org.dromara.mybatis.jpa.entity.JpaPage;
import org.dromara.mybatis.jpa.entity.JpaPageResults;
......@@ -112,9 +114,7 @@ public class JpaService <T extends JpaEntity> {
}
} catch(Exception e) {
logger.error("getMapper Exception " , e);
} finally {
}
}
return mapper;
}
......@@ -215,7 +215,7 @@ public class JpaService <T extends JpaEntity> {
totalCount = parseCount(getMapper().fetchCount(page));
}
return new JpaPageResults<T>(page.getPageNumber(),page.getPageSize(),totalPage,totalCount,resultslist);
return new JpaPageResults<>(page.getPageNumber(),page.getPageSize(),totalPage,totalCount,resultslist);
}
/**
......@@ -250,7 +250,7 @@ public class JpaService <T extends JpaEntity> {
} catch(Exception e) {
logger.error("query Exception " , e);
}
return null;
return Collections.emptyList();
}
/**
......@@ -265,7 +265,7 @@ public class JpaService <T extends JpaEntity> {
} catch(Exception e) {
logger.error("query Exception " , e);
}
return null;
return Collections.emptyList();
}
/**
......@@ -278,7 +278,7 @@ public class JpaService <T extends JpaEntity> {
} catch(Exception e) {
logger.error("findAll Exception" , e);
}
return null;
return Collections.emptyList();
}
......@@ -300,7 +300,7 @@ public class JpaService <T extends JpaEntity> {
} catch(Exception e) {
logger.error("findAll Exception " , e);
}
return null;
return Collections.emptyList();
}
/**
......@@ -325,7 +325,7 @@ public class JpaService <T extends JpaEntity> {
public T findOne(String filter , Object[] args , int[] argTypes) {
try {
List<T> findList = find(filter ,args , argTypes);
return (findList == null ||findList.size() == 0) ? null : findList.get(0);
return CollectionUtils.isEmpty(findList) ? null : findList.get(0);
} catch(Exception e) {
logger.error("findAll Exception " , e);
}
......
......@@ -51,11 +51,12 @@ public class MyBatisJpaSessionFactoryBean extends SqlSessionFactoryBean {
this.dialect = dialect;
}
@Override
protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
SqlSessionFactory factory = super.buildSqlSessionFactory();
Configuration config = factory.getConfiguration();
logger.debug("buildSqlSessionFactory : {}" , config.toString());
logger.debug("buildSqlSessionFactory : {}" , config);
for (Interceptor interceptor : interceptors) {
config.addInterceptor(interceptor);
}
......
......@@ -20,6 +20,7 @@ package org.dromara.mybatis.jpa.dialect;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import org.dromara.mybatis.jpa.entity.JpaPage;
import org.slf4j.Logger;
......@@ -44,17 +45,17 @@ public abstract class Dialect {
static {
dialectMap=new HashMap<String,String>();
dialectMap=new HashMap<>();
dialectMap.put("db2", "org.dromara.mybatis.jpa.dialect.DB2Dialect");
dialectMap.put("derby", "org.dromara.mybatis.jpa.dialect.DerbyDialect");
dialectMap.put("mysql", "org.dromara.mybatis.jpa.dialect.MySQLDialect");
dialectMap.put(DEFAULT_DIALECT, "org.dromara.mybatis.jpa.dialect.MySQLDialect");
dialectMap.put("oracle", "org.dromara.mybatis.jpa.dialect.OracleDialect");
dialectMap.put("postgresql", "org.dromara.mybatis.jpa.dialect.PostgreSQLDialect");
dialectMap.put("highgo", "org.dromara.mybatis.jpa.dialect.HighgoDialect");
dialectMap.put("sqlserver", "org.dromara.mybatis.jpa.dialect.SQLServerDialect");
_logger.trace("Dialect Mapper : \n"+dialectMap);
_logger.trace("Dialect Mapper : \n{}" ,dialectMap);
}
// constructors and factory methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
......@@ -101,7 +102,7 @@ public abstract class Dialect {
/**
* @return the dialectMap
*/
public static HashMap<String, String> getDialectMap() {
public static Map<String, String> getDialectMap() {
return dialectMap;
}
......
......@@ -107,6 +107,15 @@ public class JpaPage {
@Transient
protected String pageResultSelectUUID;
public JpaPage(){}
public JpaPage(int pageNumber , int pageSize){
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.pageable = true;
}
@JsonIgnore
public int getRows() {
return rows;
......
......@@ -136,7 +136,7 @@ public class JpaPageResults <T>{
public void pageCount(int currentPage,int pageResults,Integer recordsCount){
this.page=currentPage;
//通过总记录数和每页显示记录数计算出当前页记录数
this.total =(int) ((recordsCount%pageResults>0)?recordsCount/pageResults+1:recordsCount/pageResults);
this.total =((recordsCount%pageResults>0)?recordsCount/pageResults+1:recordsCount/pageResults);
this.records = Long.parseLong(recordsCount+"");
}
/**
......
......@@ -2,14 +2,14 @@ package org.dromara.mybatis.jpa.id;
public class IdStrategy {
public static final String SERIAL = "serial";
public static final String SERIAL = "serial";
public static final String UUID = "uuid";
public static final String UUIDHEX = "uuid.hex";
public static final String UUIDHEX = "uuid.hex";
public static final String SNOWFLAKEID = "snowflakeid";
public static final String SNOWFLAKEID = "snowflakeid";
public static final String DEFAULT = "default";
public static final String DEFAULT = "default";
}
......@@ -25,7 +25,7 @@ public class IdentifierGeneratorFactory {
private static final Logger logger = LoggerFactory.getLogger(IdentifierGeneratorFactory.class);
public static ConcurrentHashMap<String, IdentifierGenerator>identifierGeneratorMap = new ConcurrentHashMap<String, IdentifierGenerator>();
public static ConcurrentHashMap<String, IdentifierGenerator> identifierGeneratorMap = new ConcurrentHashMap<>();
public IdentifierGeneratorFactory() {
register(IdStrategy.UUID , new UUIDGenerator());
......
......@@ -37,28 +37,28 @@ public class SnowFlakeIdGenerator implements IdentifierGenerator{
/**
* 起始的时间戳
*/
private final static long START_STMP = 1480166465631L;
private static final long START_STMP = 1480166465631L;
/**
* 每一部分占用的位数
*/
private final static long SEQUENCE_BIT = 12; //序列号占用的位数
private final static long MACHINE_BIT = 5; //机器标识占用的位数
private final static long DATACENTER_BIT = 5;//数据中心占用的位数
private static final long SEQUENCE_BIT = 12; //序列号占用的位数
private static final long MACHINE_BIT = 5; //机器标识占用的位数
private static final long DATACENTER_BIT = 5;//数据中心占用的位数
/**
* 每一部分的最大值
*/
private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
private static final long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private static final long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private static final long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
/**
* 每一部分向左的位移
*/
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private static final long MACHINE_LEFT = SEQUENCE_BIT;
private static final long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private static final long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; //数据中心
private long machineId; //机器标识
......@@ -165,11 +165,11 @@ public class SnowFlakeIdGenerator implements IdentifierGenerator{
int sequenceStart = (int) (len < MACHINE_LEFT ? 0 : len - MACHINE_LEFT);
int workerStart = (int) (len < DATACENTER_LEFT ? 0 : len - DATACENTER_LEFT);
int timeStart = (int) (len < TIMESTMP_LEFT ? 0 : len - TIMESTMP_LEFT);
String sequence = sonwFlakeId.substring(sequenceStart, len);
String parseSequence = sonwFlakeId.substring(sequenceStart, len);
String workerId = sequenceStart == 0 ? "0" : sonwFlakeId.substring(workerStart, sequenceStart);
String dataCenterId = workerStart == 0 ? "0" : sonwFlakeId.substring(timeStart, workerStart);
String time = timeStart == 0 ? "0" : sonwFlakeId.substring(0, timeStart);
int sequenceInt = Integer.valueOf(sequence, 2);
int sequenceInt = Integer.valueOf(parseSequence, 2);
int workerIdInt = Integer.valueOf(workerId, 2);
int dataCenterIdInt = Integer.valueOf(dataCenterId, 2);
long diffTime = Long.parseLong(time, 2);
......
......@@ -30,7 +30,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractStatementHandlerInterceptor implements Interceptor {
protected Logger logger = LoggerFactory.getLogger(getClass());
private Logger logger = LoggerFactory.getLogger(getClass());
protected Dialect dialect;
......@@ -62,8 +62,7 @@ public abstract class AbstractStatementHandlerInterceptor implements Intercepto
StatementHandler statement = (StatementHandler) invocation.getTarget();
if (statement instanceof RoutingStatementHandler) {
MetaObject metaObject = SystemMetaObject.forObject(statement);
StatementHandler statementHandler = (StatementHandler)metaObject.getValue("delegate");
return statementHandler;
return (StatementHandler)metaObject.getValue("delegate");
}
return statement;
......@@ -71,8 +70,7 @@ public abstract class AbstractStatementHandlerInterceptor implements Intercepto
protected RowBounds getRowBounds(StatementHandler statement) {
MetaObject metaObject = SystemMetaObject.forObject(statement);
RowBounds rowBounds=(RowBounds)metaObject.getValue("rowBounds");
return rowBounds;
return (RowBounds)metaObject.getValue("rowBounds");
}
protected boolean hasBounds(RowBounds rowBounds) {
......
......@@ -48,7 +48,7 @@ import org.slf4j.LoggerFactory;
})
public class AllStatementHandlerInterceptor extends
AbstractStatementHandlerInterceptor implements Interceptor {
protected static Logger logger = LoggerFactory.getLogger(AllStatementHandlerInterceptor.class);
private static Logger logger = LoggerFactory.getLogger(AllStatementHandlerInterceptor.class);
public Object intercept(Invocation invocation) throws Throwable {
Method m = invocation.getMethod();
......
......@@ -42,7 +42,7 @@ import org.slf4j.LoggerFactory;
@Intercepts( {
@Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class ,Integer.class })})
public class StatementHandlerInterceptor extends AbstractStatementHandlerInterceptor implements Interceptor {
protected static Logger logger = LoggerFactory.getLogger(StatementHandlerInterceptor.class);
private static Logger logger = LoggerFactory.getLogger(StatementHandlerInterceptor.class);
public Object intercept(Invocation invocation) throws Throwable {
Method m = invocation.getMethod();
......@@ -73,8 +73,8 @@ public class StatementHandlerInterceptor extends AbstractStatementHandlerInterce
//判断是否select语句及需要分页支持
if (sql.toLowerCase().trim().startsWith("select")) {
JpaPage page = null;
if((parameterObject instanceof JpaPage)) {
page = (JpaPage)parameterObject;
if((parameterObject instanceof JpaPage parameterObjectPage)) {
page = parameterObjectPage;
}else if((parameterObject instanceof ParamMap)
&& ((ParamMap<?>)parameterObject).containsKey(MapperMetadata.PAGE)) {
page = (JpaPage)((ParamMap<?>)parameterObject).get(MapperMetadata.PAGE);
......@@ -90,7 +90,8 @@ public class StatementHandlerInterceptor extends AbstractStatementHandlerInterce
}
//分页标识
if(page != null && page.isPageable()){
logger.trace("prepare boundSql ==> {}" , removeBreakingWhitespace(sql));
String boundSqlRemoveBreakingWhitespace = removeBreakingWhitespace(sql);
logger.trace("prepare boundSql ==> {}" , boundSqlRemoveBreakingWhitespace);
if(statement instanceof SimpleStatementHandler){
sql = dialect.getLimitString(sql, page);
}else if(statement instanceof PreparedStatementHandler){
......@@ -100,7 +101,7 @@ public class StatementHandlerInterceptor extends AbstractStatementHandlerInterce
);
sql = dialect.getLimitString(sql, page);
}
logger.trace("prepare dialect boundSql : {}" , removeBreakingWhitespace(sql));
logger.trace("prepare dialect boundSql : {}" , boundSqlRemoveBreakingWhitespace);
metaObject.setValue("boundSql.sql", sql);
}
}
......
......@@ -91,12 +91,11 @@ public class MapperMetadata <T extends JpaEntity>{
}
public static ConcurrentMap<String, List<FieldColumnMapper>>
fieldsMap = new ConcurrentHashMap<String, List<FieldColumnMapper>>();
public static ConcurrentMap<String, List<FieldColumnMapper>> fieldsMap = new ConcurrentHashMap<>();
public static ConcurrentMap<String, String>sqlsMap = new ConcurrentHashMap<String, String>();
public static ConcurrentMap<String, String>sqlsMap = new ConcurrentHashMap<>();
public static ConcurrentMap<String, String>tableNameMap = new ConcurrentHashMap<String, String>();
public static ConcurrentMap<String, String>tableNameMap = new ConcurrentHashMap<>();
public static IdentifierGeneratorFactory identifierGeneratorFactory = new IdentifierGeneratorFactory();
......@@ -115,9 +114,9 @@ public class MapperMetadata <T extends JpaEntity>{
String schema = null;
String catalog = null;
//must use @Entity to ORM class
Entity entity =(Entity)entityClass.getAnnotation(Entity.class);
Entity entity = entityClass.getAnnotation(Entity.class);
logger.trace("entity {}" , entity);
Table table = (Table)entityClass.getAnnotation(Table.class);
Table table = entityClass.getAnnotation(Table.class);
logger.trace("table {}" , table);
if(entity != null ) {
if(entity.name() != null && !entity.name().equals("")) {
......@@ -242,7 +241,7 @@ public class MapperMetadata <T extends JpaEntity>{
logger.trace("entityClass {}" , entityClass);
Field[] fields = entityClass.getDeclaredFields();
List<FieldColumnMapper>fieldColumnMapperList=new ArrayList<FieldColumnMapper>(fields.length);
List<FieldColumnMapper>fieldColumnMapperList=new ArrayList<>(fields.length);
for (Field field : fields) {
//skip Transient field
......@@ -251,11 +250,11 @@ public class MapperMetadata <T extends JpaEntity>{
}
if (field.isAnnotationPresent(Column.class)) {
FieldColumnMapper fieldColumnMapper=new FieldColumnMapper();
FieldColumnMapper fieldColumnMapper = new FieldColumnMapper();
fieldColumnMapper.setFieldName( field.getName());
fieldColumnMapper.setFieldType(field.getType().getSimpleName());
String columnName = "";
Column columnAnnotation = (Column) field.getAnnotation(Column.class);
Column columnAnnotation = field.getAnnotation(Column.class);
fieldColumnMapper.setColumnAnnotation(columnAnnotation);
if (columnAnnotation.name() != null && !columnAnnotation.name().equals("")) {
columnName = columnAnnotation.name();
......
......@@ -58,7 +58,7 @@ public class FetchCountProvider <T extends JpaEntity>{
//多个空格 tab 替换成1个空格
String selectSql = StringUtils.lineBreak2Blank(pageResultsSqlCache.getSql());
BoundSql boundSql = (BoundSql)pageResultsSqlCache.getBoundSql();
BoundSql boundSql = pageResultsSqlCache.getBoundSql();
logger.trace("Count original SQL :\n{}" , selectSql);
StringBuffer sql = new StringBuffer(SqlSyntaxConstants.SELECT +" "+ SqlSyntaxConstants.Functions.COUNT_ONE +" countrows_ ");
......
......@@ -85,7 +85,7 @@ public class FindProvider <T extends JpaEntity>{
throw new Exception("args length < parameter placeholder");
}
String filterSqls [] = filterSql.split("\\?");
String[] filterSqls = filterSql.split("\\?");
StringBuffer sqlBuffer = new StringBuffer("");
for(int i = 0 ;i < args.length ; i++){
logger.trace("Find args[{}] {}" , i, args[i]);
......
......@@ -44,7 +44,7 @@ public class QueryProvider<T extends JpaEntity> {
if (query.getOrderBy() != null) {
sql.ORDER_BY(QueryBuilder.buildOrderBy(query));
}
logger.trace("filter By Query SQL \n{}" , sql.toString());
logger.trace("filter By Query SQL \n{}" , sql);
return sql.toString();
}
......@@ -70,12 +70,12 @@ public class QueryProvider<T extends JpaEntity> {
|| (fieldType.equals("Integer")&& fieldValue.equals("0"))
|| (fieldType.equals("Float")&& fieldValue.equals("0.0"))
|| (fieldType.equals("Double")&& fieldValue.equals("0.0"))){
// skip default field value
}else {
sql.WHERE(fieldColumnMapper.getColumnName() + " = #{" + fieldColumnMapper.getFieldName() + "}");
}
}
logger.trace("filter By Entity SQL \n{}" , sql.toString());
logger.trace("filter By Entity SQL \n{}" , sql);
return sql.toString();
}
......
package org.dromara.mybatis.jpa.query;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
public class Query {
......@@ -11,7 +14,7 @@ public class Query {
public static final String DESC = "desc";
}
ArrayList<Condition> conditions = new ArrayList<Condition>();
ArrayList<Condition> conditions = new ArrayList<>();
ArrayList<Condition> groupBy ;
......@@ -21,23 +24,23 @@ public class Query {
super();
}
public Query builder(){
public static Query builder(){
return new Query();
}
public ArrayList<Condition> getConditions() {
public List<Condition> getConditions() {
return conditions;
}
public ArrayList<Condition> getOrderBy() {
public List<Condition> getOrderBy() {
return orderBy;
}
public void joint() {
if(conditions.size() >= 1) {
if(CollectionUtils.isNotEmpty(conditions)) {
Operator lastJoint = conditions.get(conditions.size() -1).getExpression();
if(lastJoint.equals(Operator.and)
||lastJoint.equals(Operator.or)) {
||lastJoint.equals(Operator.or)){
}else {
and();
}
......@@ -310,7 +313,7 @@ public class Query {
* @param value
* @return Query
*/
public Query isNotNull(String column, Object value) {
public Query isNotNull(String column) {
joint();
conditions.add(new Condition(Operator.isNotNull,column,null));
return this;
......@@ -354,7 +357,7 @@ public class Query {
public Query groupBy(String column) {
if(groupBy == null) {
this.groupBy = new ArrayList<Condition>();
this.groupBy = new ArrayList<>();
}
groupBy.add(new Condition(Operator.group,column,""));
return this;
......@@ -362,13 +365,13 @@ public class Query {
public Query orderBy(String column,String orderType) {
if(orderBy == null) {
this.orderBy = new ArrayList<Condition>();
this.orderBy = new ArrayList<>();
}
orderBy.add(new Condition(Operator.order,column,orderType));
return this;
}
public ArrayList<Condition> getGroupBy() {
public List<Condition> getGroupBy() {
return groupBy;
}
......
......@@ -27,6 +27,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.LogFactory;
public class BeanUtil {
......@@ -65,10 +66,7 @@ public class BeanUtil {
@SuppressWarnings("rawtypes")
public static boolean isNotNull(Collection collection) {
if(collection != null && collection.size() > 0) {
return true;
}
return false;
return CollectionUtils.isNotEmpty(collection);
}
@SuppressWarnings("rawtypes")
......
......@@ -25,6 +25,8 @@ import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
......@@ -32,42 +34,41 @@ import org.slf4j.LoggerFactory;
*
*/
public class MacAddress {
public static String os;
private static final Logger logger = LoggerFactory.getLogger(MacAddress.class);
public static final String os;
static{
Properties prop = System.getProperties();
os = prop.getProperty("os.name");
LoggerFactory.getLogger(MacAddress.class).info("OS : "+os);
logger.info("OS : {}" , os);
}
public static String getAllHostMacAddress(){
String hostIpAddress="";
StringBuilder hostIpAddress = new StringBuilder();
try {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress inetAddress = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
NetworkInterface ni = netInterfaces.nextElement();
if(ni.getInetAddresses().hasMoreElements()){
inetAddress = (InetAddress) ni.getInetAddresses().nextElement();
inetAddress = ni.getInetAddresses().nextElement();
if(!inetAddress.isLoopbackAddress()){
hostIpAddress += getMac(inetAddress)+",";
LoggerFactory.getLogger(MacAddress.class).info("host MAC : "+getMac(inetAddress));
hostIpAddress.append(getMac(inetAddress)).append(",");
logger.info("host MAC : {}" ,getMac(inetAddress));
}
}
}
} catch (SocketException e) {
e.printStackTrace();
logger.error("Socket Exception",e);
}
return hostIpAddress;
return hostIpAddress.toString();
}
public static String getMac(InetAddress ia) throws SocketException {
//获取网卡,获取地址
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
//LoggerFactory.getLogger(MacAddress.class).info("mac数组长度:"+mac.length);
StringBuffer sb = new StringBuffer("");
for(int i=0; i<mac.length; i++) {
if(i!=0) {
......
......@@ -64,7 +64,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
if (string != null && !string.equals("")) {
strs = string.split(split);
}
ArrayList<String> resultList = new ArrayList<String>(0);
ArrayList<String> resultList = new ArrayList<>(0);
for (int i = 0; i < strs.length; i++) {
if (strs[i] != null&& !strs[i].equals("")) {
resultList.add(strs[i]);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册