Hibernate工具父类

实现了一个公有父类:

public abstract class AbstractADO {
    public static Logger LOG = LoggerFactory.getLogger(AbstractADO.class);
    public Class classType = null;

    public AbstractADO() {

    }

    public void init(Class classType) {
        this.classType = classType;
    }

    // 抽离事务处理机制,将session的具体处理交给lambda
    public void execute(Consumer 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 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 classType, Object id) {
        return (T)query(session -> session.get(classType, id.toString()));
    }

    public T getById(Object id) {
        return getById(classType, id);
    }

    public List getList(Class classType, int page, int perPage, int limit) {
        // 限制查询的最大条目
        if (perPage > limit) {
            return null;
        }

        return (List) query(session -> session.createQuery("from " + classType.getName())
                .setFirstResult(perPage * page).setMaxResults(perPage).list());
    }


    public List getList(Class classType, int page, int perPage) {
        return getList(classType, page, perPage, 100);
    }

    public List getList(int page, int perPage) {
        return getList(classType, page, perPage);
    }

    public List getAll(Class classType, int limit) {
        return getList(classType, 0, limit, limit);
    }

    public List getAll(Class classType) {
        return getAll(classType, 100);
    }

    public List 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 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 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();
        }
    }
}

你可能感兴趣的:(Hibernate工具父类)