📄 easyjdb.java
字号:
package com.easyjf.dbo;
import org.apache.log4j.*;
import com.easyjf.beans.BeanUtils;
import com.easyjf.beans.BeanWrapper;
import com.easyjf.dbo.config.DBOConfig;
import com.easyjf.dbo.config.XMLConfigFactory;
import com.easyjf.dbo.sql.ISqlQuery;
import com.easyjf.util.StringUtils;
import java.beans.*;
import java.sql.*;
import java.util.*;
/**
*
* <p>
* Title:EasyDBO用户接口
* </p>
*
* <p>
* Description:实现普通对象到DBO对象的自动转换,该类是用户使用EasyDBO的基本类,用户有关的数据库对象操作均可以通过该类处理.
* </p>
*
* <p>
* Copyright: Copyright (c) 2006
* </p>
*
* <p>
* Company: EasyJF开源团队-EasyDBO项目组
* </p>
*
* @author 大峡、piginzoo
* @version 1.0
*/
public class EasyJDB {
private final static Logger logger = Logger.getLogger(EasyJDB.class);
private boolean enableCache;
private String cacheName;
private DboCache innerCache;
private DBMapping mapping;
private List configFiles;
private static EasyJDB singleton;
/**
*
*/
private EasyJDBEngine dbEngine;
// 默认的构造子
public EasyJDB() {
this(null);
}
public EasyJDB(javax.sql.DataSource dataSource) {
this(dataSource, "");
}
public EasyJDB(javax.sql.DataSource dataSource,
com.easyjf.dbo.sql.ISqlQuery sqlQuery) {
this(dataSource, sqlQuery, "");
}
public EasyJDB(javax.sql.DataSource dataSource, String cacheName) {
this(dataSource, new com.easyjf.dbo.sql.MySqlQuery(), cacheName);
}
public EasyJDB(javax.sql.DataSource dataSource,
com.easyjf.dbo.sql.ISqlQuery sqlQuery, String cacheName) {
this(dataSource, sqlQuery, cacheName, false);
}
public EasyJDB(javax.sql.DataSource dataSource,
com.easyjf.dbo.sql.ISqlQuery sqlQuery, String cacheName,
boolean showSql) {
this.dbEngine = new EasyJDBEngine(dataSource, sqlQuery);
this.dbEngine.setShowSql(showSql);
this.mapping = new DBMapping();
if (StringUtils.hasText(cacheName)) {
this.enableCache = true;//使用cache
this.cacheName = cacheName;//
this.innerCache = new DboCache(cacheName);
}
}
public void loadConfigFile() {
DBOConfig dboconfig = new DBOConfig();
for (int i = 0; i < configFiles.size(); i++) {
String fileName = (String) configFiles.get(i);
java.io.InputStream in =Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
XMLConfigFactory configFactory = new XMLConfigFactory(in);
// configFactory.setMapping(this.mapping);
configFactory.init(dboconfig);
Iterator it = dboconfig.getTables().keySet().iterator();
while (it.hasNext()) {
String className = (String) it.next();
this.mapping.getMap().put(className,
dboconfig.getTables().get(className));
}
}
}
/**
* 以工厂方法的形式,提供给外部调用接口
*
* @return EasyJDB 返回EasyJDB的一个实例
*/
public static EasyJDB getInstance() {
if (singleton == null)
init();
System.out.println("使用Cache情况:"+singleton.isEnableCache());
return singleton;
}
private synchronized static void init() {
if (singleton != null)
return;
singleton = new EasyJDB();
singleton.dbEngine = EasyJDBEngine.getInstance();
singleton.mapping = DBMapping.getInstance();
try {
if (DBOConfig.getInstance().isEnableCache()) {
singleton.enableCache = true;
singleton.cacheName = DBOConfig.getInstance().getCacheName();
singleton.innerCache = new DboCache(singleton.cacheName);
}
} catch (Exception e) {
logger.error("加载EasyDBO Config配置文件错误!" + e);
}
}
/**
* 把对象obj保存到数据库中
*
* @param obj
* Object
* @return boolean
*/
public boolean add(Object obj) {
logger.debug("把对象obj保存到数据库中");
boolean ret = dbEngine.add(obj2dbo(obj));
if(ret)ret = ret & addRelativeObject(obj);
return ret;
}
private boolean addRelativeObject(Object obj) {
boolean ret = true;
DBTable table = findTable(obj.getClass());
if (table != null) {
BeanWrapper wrapper = new BeanWrapper(obj);
java.util.Iterator it = table.getClassField().entrySet().iterator();
while (it.hasNext()) {
// 尝试处理其它字段
Map.Entry en = (Map.Entry) it.next();
String propertyName = (String) en.getKey();
ClassField classField = (ClassField) en.getValue();
// System.out.println(classField.getClass()+":"+propertyName);
if (classField instanceof ManyToManyField
&& wrapper.isReadableProperty(propertyName)) {
// 处理多对多
Object value = wrapper.getPropertyValue(propertyName);
// System.out.println("值内容"+value.getClass());
if (value != null && value instanceof Collection) {
java.util.Iterator es = ((Collection) value).iterator();
while (es.hasNext()) {
Object element = es.next();
ret = ret & this.saveOrUpdate(element);
// 保存关联的第三方表
ManyToManyField field = (ManyToManyField) classField;
/*
* DBTable table2=findTable(element.getClass());
* if(table2!=null) { ManyToManyField field2=null;
* java.util.Iterator
* inf2=table2.getClassField().values().iterator();
* while(inf2.hasNext()) { ClassField
* ff=(ClassField)inf2.next();
* if(ff.getTableName().equals(field.getTableName()) &&
* ff.getType()==obj.getClass()) {
* field2=(ManyToManyField)ff; } }
*/
String sql = "insert into " + field.getTableName()
+ "(" + classField.getColumn() + ","
+ field.getTagColumn() + ") values(?,?)";
java.util.Collection paras = new java.util.ArrayList();
paras.add(wrapper.getPropertyValue(classField
.getKey()));
BeanWrapper wrapper2 = new BeanWrapper(element);
paras.add(wrapper2.getPropertyValue(field
.getTagKey()));
try {
this.execute(sql, paras);
} catch (Exception e) {
logger.error("插入多对多关系时出错!");
e.printStackTrace();
}
// }
}
}
} else if ((classField instanceof ManyToOneField)
&& wrapper.isReadableProperty(propertyName)) {
// 处理一对多
Object value = wrapper.getPropertyValue(propertyName);
if (value != null && value instanceof Collection) {
java.util.Iterator es = ((Collection) value).iterator();
while (es.hasNext()) {
Object item = es.next();
// Object
// key=wrapper.getPropertyValue(table.getId());
// BeanWrapper wi=new BeanWrapper(item);
// wi.setPropertyValue(classField.getColumn(),obj);
ret = ret & this.saveOrUpdate(item);
}
}
}
}
}
return ret;
}
/**
* 把泛数据库对象转换成类型为cls的具体对象
*
* @param dbo
* DBObject
* @param cls
* Class
* @return Object
*/
private Object dbo2obj(DBObject dbo, Class cls) {
if (dbo == null) {
return null;
}
Object obj = null;
if (cls != null) {
try {
obj = cls.newInstance();
if (cls == DBObject.class) { // 如果是原始DBO对象,则直接输出
obj = dbo;
} else {
dbo2obj(dbo, obj);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("数据库对象转换为java对象错误:" + e);
throw new EasyDBOException(e);
}
}
return obj;
}
/**
*
* @param dbo
* DBObject
* @param obj
* Object
*/
private void dbo2obj(DBObject dbo, Object obj) {
if (dbo != null) {
Map map = dbo.getValue();
DBTable table = findTable(obj.getClass());
if (table == null) {
table = dbo.getTable();
}
// this.setAutoCommit(false);
BeanWrapper wrapper = new BeanWrapper(obj);
/*
* Iterator names = map.keySet().iterator(); while (names.hasNext()) {
* String name = (String) names.next(); String popertyName =
* table.getPoperty(name); DBField field =
* table.getField(popertyName); // Class fieldType =
* table.getType(name); if (popertyName != null) { if
* (wrapper.isWritableProperty(popertyName)) { Object value =
* map.get(name); if (value != null) { try { // 对象类 if
* (com.easyjf.dbo.ClassField.class
* .isAssignableFrom(field.getClass()) ) { if(!field.isLazy())
* wrapper.setPropertyValue(popertyName, ((ClassField)
* field).loadValue(dbo,this)); } else {
* wrapper.setPropertyValue(popertyName,getRealValue(value)); } }
* catch (Exception e) { throw new EasyDBOException(e); } } } } }
*/
java.util.Iterator it = table.getAllFields().entrySet().iterator();
while (it.hasNext()) {
Map.Entry en = (Map.Entry) it.next();
DBField field = (DBField) en.getValue();
String popertyName = (String) en.getKey();
try {
if (ClassField.class.isAssignableFrom(field.getClass())) {
if(logger.isDebugEnabled())logger.debug(field.getClass());
if (field.getClass() == OneToOneField.class
&& !field.isLazy()) {
// 过滤掉OneToOne中的null属性
wrapper.setPropertyValue(popertyName,
((ClassField) field).loadValue(dbo,
this));
} else {
if (field.getClass() != OneToOneField.class
|| map.get(((ClassField) field)
.getColumn()) != null) {
if(logger.isDebugEnabled())logger.debug("加载属性:" + popertyName);
ClassFieldLazyLoader lazy = new ClassFieldLazyLoader(
dbo, this, (ClassField) field);
Class type = (field instanceof ManyToOneField
|| field instanceof ManyToManyField ? ((ManyToOneField) field)
.getFieldType()
: field.getType());
wrapper.setPropertyValue(popertyName,
net.sf.cglib.proxy.Enhancer.create(
type, lazy));
}
}
} else {
if (!field.isLazy()) {
Object value = map.get(field.getName());
if (value != null) {
wrapper.setPropertyValue(popertyName,
getRealValue(value));
}
} else {
// 作廷迟加载处理
logger.debug("普通属性廷迟加载:" + field.getName());
LazyLoader lazy = new LazyLoader(
dbo.getTable(),
field,
(java.io.Serializable) dbo.getIdValue(),
this);
wrapper.setPropertyValue((String) en.getKey(),
net.sf.cglib.proxy.Enhancer.create(
field.getType(), lazy));
}
}
} catch (Exception e) {
throw new EasyDBOException(e);
}
}
/*
* it = table.getClassField().entrySet().iterator(); while
* (it.hasNext()) { // 尝试处理其它字段 Map.Entry en = (Map.Entry)
* it.next(); String popertyName = (String) en.getKey(); ClassField
* classField = (ClassField) en.getValue();//
* table.findClassField(popertyName); if ((classField instanceof
* ManyToOneField &&
* wrapper.isWritableProperty(popertyName))||(classField instanceof
* ManyToManyField &&
* wrapper.isWritableProperty(popertyName))||classField.isLazy()) { //
* if(classField.isLazy()) //{ ClassFieldLazyLoader lazy=new
* ClassFieldLazyLoader(dbo,this,classField); Class type=(classField
* instanceof ManyToOneField||classField instanceof
* ManyToManyField?((ManyToOneField)classField).getFieldType():classField.getType());
* //if(classField.isLazy())
* wrapper.setPropertyValue(popertyName,net.sf.cglib.proxy.Enhancer.create(type,lazy));
* //else //
* wrapper.setPropertyValue(popertyName,classField.loadValue(dbo,this)); // } //
* else // wrapper.setPropertyValue(popertyName,
* classField.loadValue(dbo, this)); } }
*/
// this.commit();
}
}
private Object getRealValue(Object value) throws Exception {
Object obj = null;
if (java.sql.Blob.class.isAssignableFrom(value.getClass())) {
Blob blob = new BlobImpl((byte[]) value);
obj = blob;
} else if (java.sql.Clob.class.isAssignableFrom(value.getClass())) {
// 此处处理有一点问题
Clob clob = (Clob) value;
obj = clob.getSubString(1, (int) clob.length());
} else {
obj = value;
}
return obj;
}
/**
* 从数据库中删除obj对象所代表的行
*
* @param obj
* Object
* @return boolean
*/
public boolean del(Object obj) {
if(obj==null)return false;
boolean ret = delRelativeObject(obj);
ret = ret & dbEngine.del(obj2dbo(obj));
if (enableCache)
innerCache.removeElement(obj);
return ret;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -