Hibernate工具父類

實(shí)現(xiàn)了一個(gè)公有父類:

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;
    }

    // 抽離事務(wù)處理機(jī)制,將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可以自己用關(guān)系實(shí)體做映射,所以不需要此方法
    @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
        {
            // 采用默認(rèn)的hibernate.cfg.xml來(lái)啟動(dòng)一個(gè)Configuration的實(shí)例
            Configuration cfg = new Configuration()
                    .configure();
            cfg.addResource("hibernate.cfg.xml");
            // 以Configuration實(shí)例來(lái)創(chuàng)建SessionFactory實(shí)例
            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();
        }
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒(méi)有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,666評(píng)論 1 32
  • 本部分內(nèi)容用來(lái)指導(dǎo)程序員怎樣才能設(shè)計(jì)出更加有用、健壯、靈活的類和接口。內(nèi)容導(dǎo)圖如下: 1.使類和成員的可訪問(wèn)性最小...
    塞外的風(fēng)閱讀 663評(píng)論 0 1
  • 父類引用指向子類對(duì)象指的是: 例如父類Animal,子類Cat,Dog。其中Animal可以是類也可以是接口,Ca...
    木有魚丸啦閱讀 995評(píng)論 0 4
  • 昨天晩上,很意外接到孩爸打來(lái)的電話,是的,你沒(méi)有聽(tīng)錯(cuò),是意外,像我?guī)е⒆釉诶牙鸭易x書,星期五晩上孩爸就會(huì)來(lái)接我們...
    小蝸牛的尾巴閱讀 444評(píng)論 0 5
  • 在我上大學(xué)那個(gè)時(shí)候?qū)W開(kāi)車還不是很普遍,不像現(xiàn)在駕照基本是大學(xué)生的標(biāo)準(zhǔn)配備了。雖然很早我家就有車,但是基本跟我是沒(méi)什...
    寅穎閱讀 308評(píng)論 1 2

友情鏈接更多精彩內(nèi)容