4 Replies Latest reply on Nov 29, 2005 1:19 PM by Seth Ladd

    contradicting constraints and statements issue order

    Yevgen Bushuyev Newbie

      Hi.
      I need to make statements to be issued to the database in an original order (delete, insert as they appears in code) rather then as hibernate default insert first then delete.
      In a bit more details, i have two entities A and B, such that
      A.java

      @Entity(access=AccessType.FIELD)
      public class A implements Serializable{
      ...
       @OneToMany(mappedBy = "a", cascade = CascadeType.ALL)
       private Collection<B> bs;
      ...
      
       @PrePersist
       @PreUpdate
       public void validate(){
       if (bs == null || bs.size() == 0) {
       throw new RuntimeException("xxx");
       }
       }
      .....
      


      B.java
      @Table(
       uniqueConstraints={@UniqueConstraint(columnNames={"name", "a_id"})}
      )
      public class B implements Serializable{
      ...
       B(String name, A a) {
       this.name = name;
       this.a = a;
       }
      
       @Id(generate = GeneratorType.AUTO)
       private int id;
      
       private String name;
      
       @ManyToOne
       private A a;
      }
      


      besides this i need to validate A in preUpdate/Persist that there is at least one element in bs collection. Finally i need to execute following code:

       A a = new A();
       B b1 = new B(a, "x");
       a.addB(b1);
       manager.persist(a);
       a.removeB(b1);
       manager.remove(b1);
       a.addB(new B(a, "x"));
      
       manager.flush();
      


      but it gives me Violation of UNIQUE KEY constraint since it tries to insert firts, then delete. On the other hand if i try to flush after remove i got validator exception if A also was modified in a some way.
      Any suggestions? It would be greate if validation could be palced in a callback method to be called on commit.

      wbr, eugen.