代码之家  ›  专栏  ›  技术社区  ›  Tim

Hibernate验证器:hbm2ddl忽略EmbeddedId约束

  •  5
  • Tim  · 技术社区  · 15 年前


    我在postgresql8.3上使用Hibernate核心、注解和验证器。

    @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而不是@embeddeble中的其他字段),但它似乎不想工作。。

    1 回复  |  直到 15 年前
        1
  •  0
  •   soufrk    7 年前

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

    实体和复合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.12 , H2:1.4.196 ). 测试失败。