【问题标题】:Hibernate Validator: EmbeddedId constraint ignored by hbm2ddlHibernate Validator:hbm2ddl 忽略 EmbeddedId 约束
【发布时间】:2010-10-17 07:54:35
【问题描述】:

这里有一个相当具体的问题,但它已经困扰我一天了:
我在 PostgreSQL 8.3 上使用 Hibernate Core、注释和验证器。

我有以下课程设置:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Entry {
    @EmbeddedId
    protected EntryPK       entryPK;
    @ManyToMany
    private Set<Comment>    comments    = new HashSet<Comment>();
...

@Embeddable
public class EntryPK implements Serializable {
    @ManyToOne(cascade = CascadeType.ALL)
    private Database    database;

    @Length(max = 50)
    @NotEmpty
    private String      pdbid;
...

我希望在我的 PostgreSQL 数据库中看到长度约束转换为长度约束(它适用于 @Entity 内的其他字段,而不是 @Embeddable 的),但它似乎不想工作..
即使使用 @IdClass 而不是 @EmbeddedId 并对 @Entity 中的匹配字段应用长度约束也不能解决此问题:数据库字段仍然是 varchar 255(对于我的需要来说,大约 250 太大了)。
有人可能会说我不应该关心这个级别的细节,但是我的强迫症方面拒绝放手.. ;) 是否不可能在 EmbeddedId 中使用 Hibernate Validator Annotations 并让 hbm2ddl 将约束应用于数据库字段?

【问题讨论】:

  • 只是快速跟进:最终选择了不同的实现(使用生成的 ID(所以是的,我投降了;)),但我猜这可能是功能请求的候选者/向 hibernate-validator 项目报告错误..
  • 我想我可能遇到了同样的问题。请求@Tim 查看下面发布的代码。

标签: hibernate validation hbm2ddl


【解决方案1】:

没有答案。经历相同的行为。请作者识别以下代码是否与问题陈述一致。

实体和复合 ID 类。

@Embeddable
public class MyComposite implements Serializable {
    private static final long serialVersionUID = 5498013571598565048L;

    @Min(0)
    @Max(99999999)
    @Column(columnDefinition = "INT(8) NOT NULL", name = "id", nullable = false)
    private Integer id;

    @NotBlank
    @NotEmpty
    @Column(columnDefinition = "VARCHAR(8) NOT NULL", name = "code", length = 8, nullable = false)
    private String code;
    // plus getters & setters.
}

@Entity
@Table(name = "some_entity_table")
public class MyEntity {
    @EmbeddedId
    private MyComposite composite;

    public MyComposite getComposite() {
        return composite;
    }

    public void setComposite(MyComposite composite) {
        this.composite = composite;
    }
}

类的单元测试

@Test
public void createWithIdOutOfRangeTest(){
    Exception exception = null;
    MyEntity input = new MyEntity();
    MyEntity output = null;
    MyComposite id = new MyComposite();
    // EITHER THIS
    id.setId(123456789);
    id.setCode("ABCDEFG");
    // OR THIS
    id.setId(12345678);
    id.setCode("        ");
    input.setComposite(id);
    try {      
      output = service.create(input);
    } catch (Exception e) {
      exception = e;
    }
    Assert.assertNotNull("No exception inserting invalid id !!", exception);
    Assert.assertTrue("There was some other exception !!", exception instanceof ConstraintViolationException);
}

正如问题中所述,将无效值传递给复合键字段(Hibernate-core:5.0.12H2:1.4.196)没有任何异常。测试失败。

【讨论】:

  • 感谢这里的扩展示例;不能确定这是否是同一个问题,因为它已经八年了,并且从那以后有很多休眠更新。 :) 在此过程中,我选择了 Flyway 来管理我的数据库架构和迁移;也许这对你也有用。
猜你喜欢
  • 1970-01-01
  • 2016-11-04
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多