我正在尝试使用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();