Hibernate工具父类
2019-05-21 本文已影响0人
万里凪
实现了一个公有父类:
public abstract class AbstractADO<T> {
public static Logger LOG = LoggerFactory.getLogger(AbstractADO.class);
public Class<T> classType = null;
public AbstractADO() {
}
public void init(Class<T> classType) {
this.classType = classType;
}
// 抽离事务处理机制,将session的具体处理交给lambda
public void execute(Consumer<Session> consumer) {
Transaction transaction = null;
Session session = HibernateUtil.getSession();
try {
transaction = session.beginTransaction();
consumer.accept(session);
transaction.commit();
} catch (HibernateException e) {
LOG.error("transaction failed", e);
if (transaction != null) {
transaction.rollback();
}
}
}
public Object query(Function<Session, Object> supplier) {
Object result = null;
Session session = HibernateUtil.getSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
result = supplier.apply(session);
transaction.commit();
} catch (HibernateException e) {
LOG.error("query failed", e);
if (transaction != null) {
transaction.rollback();
}
}
return result;
}
public void addEntity(T t) {
execute(session -> session.save(t));
}
public void removeEntity(T t) {
execute(session -> session.delete(t));
}
public void updateEntityById(T t) {
execute(session -> session.update(t));
}
public T getById(Class<T> classType, Object id) {
return (T)query(session -> session.get(classType, id.toString()));
}
public T getById(Object id) {
return getById(classType, id);
}
public List<T> getList(Class<T> classType, int page, int perPage, int limit) {
// 限制查询的最大条目
if (perPage > limit) {
return null;
}
return (List<T>) query(session -> session.createQuery("from " + classType.getName())
.setFirstResult(perPage * page).setMaxResults(perPage).list());
}
public List<T> getList(Class<T> classType, int page, int perPage) {
return getList(classType, page, perPage, 100);
}
public List<T> getList(int page, int perPage) {
return getList(classType, page, perPage);
}
public List<T> getAll(Class<T> classType, int limit) {
return getList(classType, 0, limit, limit);
}
public List<T> getAll(Class<T> classType) {
return getAll(classType, 100);
}
public List<T> getAll() {
if (classType != null) {
return getAll(classType);
} else {
LOG.error("classType cannot be null", new IllegalArgumentException("classType cannot be null"));
return null;
}
}
public long count(Class<T> classType) {
return ((Long) query(session -> session.createQuery("select count(*) from " + classType.getName()).uniqueResult())).longValue();
}
public long count() {
if (classType != null) {
return count(classType);
} else {
LOG.error("classType cannot be null", new IllegalArgumentException("classType cannot be null"));
return 0;
}
}
// hibernate可以自己用关系实体做映射,所以不需要此方法
@Deprecated
public static String getMappingName(Class<?> classType) {
return classType.getAnnotation(Table.class).name();
}
}
另外这是HibernateUtil
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ThreadLocal<Session> tlSession = new ThreadLocal<>();
static
{
try
{
// 采用默认的hibernate.cfg.xml来启动一个Configuration的实例
Configuration cfg = new Configuration()
.configure();
cfg.addResource("hibernate.cfg.xml");
// 以Configuration实例来创建SessionFactory实例
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties())
.build();
sessionFactory = cfg.addAnnotatedClass(TUserEntity.class)
.addAnnotatedClass(TReplyEntity.class)
.addAnnotatedClass(TTopicEntity.class)
.addAnnotatedClass(StudentEntity.class)
.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static Session openSession() {
Session s = tlSession.get();
if (s == null) {
s = sessionFactory.openSession();
tlSession.set(s);
}
return s;
}
public static Session getSession() {
return openSession();
}
public static void close() {
Session s = tlSession.get();
if (s != null) {
s.close();
}
}
}