簡體   English   中英

Hibernate更新對象的非引用字段

[英]Hibernate update non-reference fields of object

我想使用Java,Spring Data / MVC / DI和Hibernate定義類似REST的API來開發CMS。

我有以下模型實體:

  • 有多個Article
  • 每篇文章都有多個Section
  • 每個部分都可以包含子部分和/或Item

所有這些實體都具有自己的屬性(例如名稱,類型等),但是很明顯,它們是指其聚合的實體。 我需要為每個這樣的實體定義CRUD API方法。

我決定從教條化的REST中脫穎而出,當我進行修改時,我只需要傳遞特定於實體的屬性(例如名稱,類型等),但不會影響聚合。 因此,我有以下端點:

  • 發布/articles -創建文章,無版塊
  • put /articles/{article_id} -更新基本文章屬性,不影響版面
  • 發布/articles/{article_id}/sections在文章中創建一個部分
  • 刪除/articles/{article_id}/sections/{section_id} -從文章中刪除該部分
  • put /articles/{article_id}/sections/{section_id} -更新基本版塊屬性,不影響擁有文章的屬性,也不影響匯總的版塊和項目
  • 等等...

所以我的問題是:

收到修改請求后,我將獲得元素的所有基本屬性以及擁有的實體標識符。 如何有效地將它們與數據庫中的現有關系結合起來,以便保留所有它們並修改基本屬性,而無需一一復制所有屬性。 這是文章-部分關系的示例。

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

您需要休眠session.merge(object_name);

鏈接: 來自Hibernate文檔

Webapp編輯功能的示例:

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

如果這不是您想要的,請告訴我,我將刪除答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM