Hibernate mapping a Map (HashMap) always add new row instead to update

时间:2018-05-28 18:50:50

标签: hibernate spring-data-jpa hibernate-mapping

I'm trying to make an Entity to support localization.

Entity - RoadAssistance

@Entity
@DynamicUpdate
public class RoadAssistance{

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Long id;



 /* Localization ....*/
 @MapKeyColumn(name = "locale")
 @MapKeyType(value = @Type(type = "java.util.Locale"))
 @OneToMany(cascade = CascadeType.ALL, mappedBy = "roadAssistance")
 Map<Locale, RoadAssistanceI18n> roadAssistanceI18n = new HashMap<>();


 /*Map Helper method for locale*/
 public RoadAssistanceI18n getRoadAssistanceI18n(Locale locale) {
    return roadAssistanceI18n.get(locale);
 }

 /// GETTERS AND SETTRE // W/O equals and hashCode implementation..

}

Entity - RoadAssistanceI18n

@Entity
@Table(name = "road_assistance_i18n")
public class RoadAssistanceI18n{

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Column(name = "id")
   private Long id;

  private String address;

  @Lob
  private String description;

  @ManyToOne
  RoadAssistance roadAssistance;

  /// GETTERS AND SETTRE // W/O equals and hashCode implementation..
}

And in the view (Thymeleaf) I have the following

<div class="col-sm-8 offset-sm-2 mt-3">
  <textarea data-th-field="*{roadAssistanceI18n[__${#locale}__].description}" rows="10" class="form-control" id="description" name="description"></textarea>
</div>

enter image description here

For the persistence, I'm using Spring data. Everything is working perfect and I can add/view the description in different languages and it works. The problem is that when I update the description, in the database table I get new rows for every update. I'm working with the reference from the persisted entity and override the map from there..

1 个答案:

答案 0 :(得分:1)

从您的HTML中,我看不到您发送当前编辑实体的ID的部分。问题可能是您持有一个RoadAssistanceI18n实体,其中id为null,这将导致数据库中的新条目。如果正确设置了id,Hibernate将更新值而不是创建新条目。