komal
komal

Reputation: 1

Saving huge lists of objects taking lot of time

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

Upvotes: 0

Views: 1130

Answers (1)

Premraj
Premraj

Reputation: 7902

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.

Upvotes: 1

Related Questions