开发者

Saving huge lists of objects taking lot of time

开发者 https://www.devze.com 2023-03-07 23:10 出处:网络
I am trying to do some big lists of object saving using hibernate.. problem is before saving I need to confirm if a record with same field data already exists if yes then need to fetch its id and cre

I am trying to do some big lists of object saving using hibernate..

problem is before saving I need to confirm if a record with same field data already exists if yes then need to fetch its id and create an association in another table.开发者_运维技巧. else make a new entry and a new insert in the association table for the same..

Please guide me how I can improve the save time..

following is how the save is done..

    Session session = SchemaManager.getDatabaseSession("com.server.domin.PublicaccountBehavior");
    try {
        List<Post> posts = this.getAllPosts();
        Transaction transaction = session.beginTransaction();
        for (Post post : posts) {
            Behavior behavior = new Behavior();
            behavior.setElementValue(val);
            behavior.setIsDeleted(false);
            Date now = new Date();
            behavior.setCreatedOn(now);
            behavior.setModifiedOn(now);
            PublicaccountType type = new PublicaccountType();
            type.setId(3L);
            behavior.setPublicaccountType(type);

            PublicaccountBehavior publicaccountBehavior = new PublicaccountBehavior();
            publicaccountBehavior.setBehavior(behavior);
            publicaccountBehavior.setPublicAccount(account);
            publicaccountBehavior.setTimeOfBookmark(post.getTimeAsDate());
            publicaccountBehavior.setCreatedOn(now);
            publicaccountBehavior.setModifiedOn(now);
            try {

                Behavior behav;
                List list2 = session.createQuery("from Behavior where elementValue = :elementVal").setString("elementVal",
                        behavior.getElementValue()).list();
                if (list2.size() > 0) {
                    behav = (Behavior) list2.get(0);
                    publicaccountBehavior.setBehavior(behav);
                } else {
                    Long id = (Long) session.save(behavior);
                    behavior.setId(id);
                    publicaccountBehavior.setBehavior(behavior);
                }
                session.saveOrUpdate(publicaccountBehavior);

            } catch (HibernateException e) {
                e.printStackTrace();
            }
        }
        transaction.commit();


When you are saving a new object - flush() and then clear() the session regularly in order to control the size of the first-level cache. which will enhance the performance.

example is explained in hibernate docs.

0

精彩评论

暂无评论...
验证码 换一张
取 消