保存庞大的对象列表需要花费大量时间

时间:2011-05-21 13:03:32

标签: java hibernate bulkinsert save

我正在尝试使用hibernate做一些大对象保存列表..

问题是在保存之前我需要确认是否已经存在具有相同字段数据的记录,如果是,则需要获取其id并在另一个表中创建关联..否则在关联表中创建新条目和新插入同样的..

请指导我如何改善节省时间..

以下是保存的方式..

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

1 个答案:

答案 0 :(得分:1)

当您保存新对象时 - flush()然后定期清除()会话以控制第一级缓存的大小。这将提高性能。

示例在hibernate docs中解释。

相关问题