public class HibernateUtil {
public static boolean showMCHitLog = false;
public static Logger log = LoggerFactory.getLogger(HibernateUtil.class);
public static Map, String> beanKeyMap = new HashMap, String>();
private static SessionFactory sessionFactory;
public static void init() {
sessionFactory = buildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Throwable insert(Object o) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
try {
session.save(o);
session.getTransaction().commit();
} catch (Throwable e) {
log.error("0要insert的数据{}", o == null ? "null" : JSONObject
.fromObject(o).toString());
log.error("0保存出错", e);
session.getTransaction().rollback();
return e;
}
return null;
}
/**
* FIXME 不要这样返回异常,没人会关系返回的异常。
*
* @param o
* @return
*/
public static Throwable save(Object o) {
Session session = sessionFactory.getCurrentSession();
Transaction t = session.beginTransaction();
boolean mcOk = false;
try {
if (o instanceof MCSupport) {
MCSupport s = (MCSupport) o;// 需要对控制了的对象在第一次存库时调用MC.add
MC.update(o, s.getIdentifier());// MC中控制了哪些类存缓存。
mcOk = true;
session.update(o);
} else {
session.saveOrUpdate(o);
}
t.commit();
} catch (Throwable e) {
log.error("1要save的数据{},{}", o, o == null ? "null" : JSONObject
.fromObject(o).toString());
if (mcOk) {
log.error("MC保存成功后报错,可能是数据库条目丢失。");
}
log.error("1保存出错", e);
t.rollback();
return e;
}
return null;
}
public static Throwable update(Object o) {
Session session = sessionFactory.getCurrentSession();
Transaction t = session.beginTransaction();
try {
if (o instanceof MCSupport) {
MCSupport s = (MCSupport) o;// 需要对控制了的对象在第一次存库时调用MC.add
MC.update(o, s.getIdentifier());// MC中控制了哪些类存缓存。
session.update(o);
} else {
session.update(o);
}
t.commit();
} catch (Throwable e) {
log.error("1要update的数据{},{}", o, o == null ? "null" : JSONObject
.fromObject(o).toString());
log.error("1保存出错", e);
t.rollback();
return e;
}
return null;
}
public static T find(Class t, long id) {
String keyField = getKeyField(t);
if (keyField == null) {
throw new RuntimeException("类型" + t + "没有标注主键");
}
if (!MC.cachedClass.contains(t)) {
return find(t, "where " + keyField + "=" + id, false);
}
T ret = MC.get(t, id);
if (ret == null) {
if (showMCHitLog)
log.info("MC未命中{}#{}", t.getSimpleName(), id);
ret = find(t, "where " + keyField + "=" + id, false);
if (ret != null) {
if (showMCHitLog)
log.info("DB命中{}#{}", t.getSimpleName(), id);
MC.add(ret, id);
} else {
if (showMCHitLog)
log.info("DB未命中{}#{}", t.getSimpleName(), id);
}
} else {
if (showMCHitLog)
log.info("MC命中{}#{}", t.getSimpleName(), id);
}
return ret;
}
public static T find(Class t, String where) {
return find(t, where, true);
}
public static T find(Class t, String where, boolean checkMCControl) {
if (checkMCControl && MC.cachedClass.contains(t)) {
// 请使用static T find(Class t,long id)
throw new BaseException("由MC控制的类不能直接查询DB:" + t);
}
Session session = sessionFactory.getCurrentSession();
Transaction tr = session.beginTransaction();
T ret = null;
try {
// FIXME 使用 session的get方法代替。
String hql = "from " + t.getSimpleName() + " " + where;
Query query = session.createQuery(hql);
ret = (T) query.uniqueResult();
tr.commit();
} catch (Exception e) {
tr.rollback();
log.error("list fail for {} {}", t, where);
log.error("list fail", e);
}
return ret;
}
/**
* 通过指定key值来查询对应的对象
*
* @param t
* @param name
* @param where
* @return
*/
public static T findByName(Class extends MCSupport> t, String name,
String where) {
Class extends MCSupport> targetClz = t;// .getClass();
String key = targetClz.getSimpleName() + ":" + name;
Object id = MC.getValue(key);
T ret = null;
if (id != null) {
log.info("id find in cache");
ret = (T) find(targetClz, Long.parseLong((String) id));
return ret;
} else {
ret = (T) find(targetClz, where, false);
}
if (ret == null) {
log.info("no record {}, {}", key, where);
} else {
MCSupport mc = (MCSupport) ret;
long mcId = mc.getIdentifier();
log.info("found id from DB {}#{}", targetClz.getSimpleName(), mcId);
MC.add(key, mcId);
ret = (T) find(targetClz, mcId);
}
return ret;
}
/**
* @param t
* @param where
* 例子: where uid>100
* @return
*/
public static List list(Class t, String where) {
Session session = sessionFactory.getCurrentSession();
Transaction tr = session.beginTransaction();
List list = Collections.EMPTY_LIST;
try {
String hql = "from " + t.getSimpleName() + " " + where;
Query query = session.createQuery(hql);
list = query.list();
tr.commit();
} catch (Exception e) {
tr.rollback();
log.error("list fail for {} {}", t, where);
log.error("list fail", e);
}
return list;
}
public static SessionFactory buildSessionFactory() {
log.info("开始构建hibernate");
String path = "classpath*:spring-conf/applicationContext.xml";
ApplicationContext ac = new FileSystemXmlApplicationContext(path);
sessionFactory = (SessionFactory) ac.getBean("sessionFactory");
log.info("结束构建hibernate");
return sessionFactory;
}
public static Throwable delete(Object o) {
if (o == null) {
return null;
}
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
try {
if (o instanceof MCSupport) {
MCSupport s = (MCSupport) o;// 需要对控制了的对象在第一次存库时调用MC.add
MC.delete(o.getClass(), s.getIdentifier());// MC中控制了哪些类存缓存。
}
session.delete(o);
session.getTransaction().commit();
} catch (Throwable e) {
log.error("要删除的数据{}", o);
log.error("出错", e);
session.getTransaction().rollback();
return e;
}
return null;
}