【问题标题】:Validation not fired if I just clear an @OneToMany relation如果我只是清除 @OneToMany 关系,则不会触发验证
【发布时间】:2015-07-28 18:24:11
【问题描述】:

我在使用 JPA 2.0 和 Hibernate 更新实体时遇到了问题(我没有与其他提供商进行测试)。这是我的实体(为简洁起见):

@Entity
public class CriterioDefinicaoImpFederais implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name="criterio_definicao_imp_federais", sequenceName="criterio_definicao_imp_federais")
    @GeneratedValue(generator="criterio_definicao_imp_federais", strategy=GenerationType.AUTO)
    private Long id;

    @Column(length=100)
    @NotNull
    @TextoValido(min=1, max=100)
    private String descricao = "";

    //Other fields ommited

    @NotEmpty
    @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="criterio")
    //Bidirectional association
    private List<GrupoCriterioImpFederais> grupos = new ArrayList<>();

    public Long getId() {
        return id;
    }

    public void addGrupo(GrupoCriterioImpFederais grupo) {
        grupo.setCriterio(this);
        this.grupos.add(grupo);
    }

    public void removerGrupo(GrupoCriterioImpFederais grupo) {
        grupos.remove(grupo);
        grupo.setCriterio(null);
    }

    //Other methods ommited
}

假设我尝试保留一个新的 CriterioDefinicaoImpFederais 实例。验证效果很好,包括字段 grupos 上的 @NotEmpty。 然后我加载持久化的实例,清除 grupos 列表(调用 removerGrupo)并尝试更新(使用 JPA 2.0 合并)实例。

此时,不会触发对 grupos (@NotEmpty) 的验证。但是,如果我更改 CriterioDefinicaoImpFederais 的另一个字段(例如 descicao),则会触发所有验证,包括对 grupos 的验证。

这是正确的行为吗?或者我错过了什么?有没有办法触发验证?

Ps:我尝试在合并后调用flush,没有成功。

加载和更新对象的代码: 要加载,我使用以下 hql:

//This is critRepo.porId
String sql = "select distinct c from CriterioDefinicaoImpFederais c "
        + "  join fetch c.licenca "
        + "  join fetch c.grupos g "
        + "where "
        + "  c.id = :id ";

这是对象持久化后执行的代码:

    em.getTransaction().begin();
    CriterioDefinicaoImpFederais outro = critRepo.porId(criterio.getId());
    em.getTransaction().commit();
    em.clear();
    outro.removerGrupo(outro.getGrupos().get(0));
    outro.removerGrupo(outro.getGrupos().get(0));
    em.getTransaction().begin();
    //This method calls merge
    critRepo.salvar(outro);
    em.getTransaction().commit();

谢谢!

【问题讨论】:

  • 嗨,你能把代码贴在你检索和更新实体的地方吗?

标签: java hibernate validation jpa merge


【解决方案1】:

我尚未对此进行验证,但这可能是因为您没有通过符合 Java Bean 规范的设置器访问该值。

如果你通过普通的setter将它设置为一个新的空集合试试。

【讨论】:

  • @Jean 感谢您的回答。我创建了一个新方法 setGrupos 并调用了 setGrupos(new ArrayList&lt;&gt;()); 并得到了相同的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 2015-05-20
  • 2015-12-13
  • 1970-01-01
相关资源
最近更新 更多