我想使用 Java、Spring Data/MVC/DI、Hibernate 定义类似 REST 的 API 来开发一个 CMS。
我有以下模型实体:
- 有多个
文章
- 每篇文章都有多个
部分
- 每个部分可以有子部分和/或
Item
所有这些实体都有自己的属性(例如名称、类型等),但很明显它们指的是它们的聚合实体。我需要为每个这样的实体定义 CRUD API 方法。
我决定稍微偏离教条式的 REST,当我进行修改时,我只需要传入特定于实体的属性(如名称、类型等),但不会影响聚合。因此我有这样的端点:
- post
/articles
- 创建文章,无章节 - put
/articles/{article_id}
- 更新基本文章属性,不影响章节 - post
/articles/{article_id}/sections
- 在文章中创建一个部分 - delete
/articles/{article_id}/sections/{section_id}
- 从文章中删除该部分 - put
/articles/{article_id}/sections/{section_id}
- 更新基本版 block 属性,不影响拥有文章属性,也不影响聚合版 block 和项目 - 等等...
所以我的问题是:
当我收到修改请求时,我会获取该元素的所有基本属性以及所属实体标识符。如何才能有效地将它们与数据库中现有的关系结合起来,以便我保留所有它们并修改基本属性,而不需要将所有属性一一复制。这是文章-部分关系的示例。
public void modifySection(int articleId, int sectionId, Section section) {
assert(article.owns(sectionId));
Section dbSection = sectionDao.findOne(sectionId);
copyOverProperties(section, dbSection); // this is the thing I do not know how to do
sectionDao.save(dbSection);
}
最佳答案
您需要 hibernates session.merge(object_name);
我们的网络应用程序的编辑功能示例:
@Repository
public class GroupCanvasDAOImpl implements GroupCanvasDAO {
private final SessionFactory sessionFactory;
@Autowired
public GroupCanvasDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void editGroupCanvas(GroupCanvas groupCanvas) {
Session session = this.sessionFactory.getCurrentSession();
GroupCanvas groupCanvas1 = (GroupCanvas) session.get(GroupCanvas.class, groupCanvas.getMcanvasid());
// Below 2 steps are not necessary if object was retrieved from DB and //then persisted back-again. If it was newly created to replace an //old-one, then the below 2 lines are needed.
groupCanvas.setGroupAccount(groupCanvas1.getGroupAccount());
groupCanvas.setCanvasowner(groupCanvas1.getCanvasowner());
session.merge(groupCanvas);
session.flush();
}
}
}
如果这不是您要找的内容,请告诉我,我会删除我的答案。
关于java - Hibernate更新对象的非引用字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33823624/