spring data jpa save 返回 主鍵問題

調試時發現,如果調用 Repository 的 save 方法時,對應的主鍵,還是爲空。以爲是什麼bug。

後面查閱資料發現。其實是在返回值中,而不是傳入值中。

查看SimpleJpaRepository源碼,調試發現,如果是走persist(新增,判斷是否新,是看是不是null,如果主鍵是空字符串,也是走的merge)。 傳入的對象裏面的主鍵會有值。

如果是走merge,走完了,傳入的對象不會有值,而是返回的 裏面有值。

@Transactional
public <S extends T> S save(S entity) {

   if (entityInformation.isNew(entity)) {
      em.persist(entity);
      return entity;
   } else {
      return em.merge(entity);
   }
}

User aaa=save(user);

如上,user 如果 主鍵爲null的時候,user和aaa是一樣的,都有主鍵。如果主鍵不爲null,比如空字符,或者更新的時候(內部判斷不是isNew的時候),user裏面主鍵還是和原來一樣,空的,而aaa中是有值的。

附上 isNew的代碼。  AbstractEntityInformation 類中。

public boolean isNew(T entity) {

   ID id = getId(entity);
   Class<ID> idType = getIdType();

   if (!idType.isPrimitive()) {
      return id == null;
   }

   if (id instanceof Number) {
      return ((Number) id).longValue() == 0L;
   }

   throw new IllegalArgumentException(String.format("Unsupported primitive id type %s!", idType));
}

 

我的實體類主鍵代碼如下

@Id
@GeneratedValue (generator = "pk")
@GenericGenerator (name = "pk", strategy = "uuid2")
@Column (name = "Role_Guid")
public String getRoleGuid() {
   return this.roleGuid;
}

 

結論,用返回的對象就對了。

參考:https://stackoverflow.com/questions/16351156/spring-data-jpa-save-can-not-get-id

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章