ssjygl-xsct-service/ssjygl-xsx-common/src/main/java/com/cowr/common/base/BaseModel.java

122 lines
2.8 KiB
Java

package com.cowr.common.base;
import com.alibaba.fastjson.annotation.JSONField;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.IBean;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.cowr.common.Const;
import com.cowr.common.utils.StrUtil;
public abstract class BaseModel<M extends Model<M>> extends Model<M> implements IBean {
private static final Log log = Log.getLog(BaseModel.class);
private static final String tablename = "";
public String getTablename() {
return tablename;
}
/**
* 判断是否存在该字段
*
* @param colunm
* @return
*/
public boolean hasColunm(String colunm) {
return _getTable().getColumnTypeMap().containsKey(colunm);
}
/**
* 判断是否有 del 字段
*
* @return
*/
public boolean hasDelKey() {
return hasColunm(Const.LOGIC_DEL_KEY);
}
@JSONField(serialize = false)
public String[] getPKey() {
return _getTable().getPrimaryKey();
}
/**
* 按主键查找
*
* @return
*/
public M findByPk() {
Table table = _getTable();
String[] pKeys = table.getPrimaryKey();
if (pKeys == null) {
log.debug(table.getName() + " 未找到主键字段");
pKeys = new String[0];
}
Object[] vals = new Object[pKeys.length];
for (int i = 0; i < pKeys.length; i++) {
vals[i] = get(pKeys[i]);
}
if (vals.length == 1) {
return findById(vals[0]);
} else {
return findByIds(vals);
}
}
/**
* 按主键检查是否存在
*
* @return boolean
*/
public boolean checkExistsByPk() {
return findByPk() != null;
}
/**
* 按字段查询 model
*
* @param columns
* @return
*/
public M findByColumns(String... columns) {
Object[] vals = new Object[columns.length];
for (int i = 0; i < columns.length; i++) {
vals[i] = get(columns[i]);
}
String sql = StrUtil.findFirstByColumnsSql(_getTable().getName(), columns);
return findFirst(sql, vals);
}
/**
* 按字段查询对象是否存在
*
* @param columns
* @return
*/
public boolean checkDuplicate(String... columns) {
return findByColumns(columns) != null;
}
/**
* 浅拷贝
*
* @return
*/
public M clone() {
try {
Model<?> ar = this.getClass().newInstance();
ar._setAttrs(this._getAttrs());
return (M) ar;
} catch (InstantiationException | IllegalAccessException e) {
log.error(e.getMessage(), e);
}
return null;
}
}