Hibernate工具父类

实现了一个公有父类:

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,834评论 1 32
  • 本部分内容用来指导程序员怎样才能设计出更加有用、健壮、灵活的类和接口。内容导图如下: 1.使类和成员的可访问性最小...
    塞外的风阅读 711评论 0 1
  • 父类引用指向子类对象指的是: 例如父类Animal,子类Cat,Dog。其中Animal可以是类也可以是接口,Ca...
    木有鱼丸啦阅读 1,026评论 0 4
  • 昨天晩上,很意外接到孩爸打来的电话,是的,你没有听错,是意外,像我带着孩子在姥姥家读书,星期五晩上孩爸就会来接我们...
    小蜗牛的尾巴阅读 468评论 0 5
  • 在我上大学那个时候学开车还不是很普遍,不像现在驾照基本是大学生的标准配备了。虽然很早我家就有车,但是基本跟我是没什...
    寅颖阅读 323评论 1 2

友情链接更多精彩内容