stefanopulze
stefanopulze

Reputation: 59

Hibernate save collection

I'm using Hibernate 4 (with Spring) to persist my object into database. I have some issue when I try save parent with a collection children.

My Table:

| A | => PK (Composite) [String + Integer]
| B | => PK (Composite) [Stirng + Integer] + Integer

Naturaly the PK of B is composite with same PK of A and A contain a collection of B.

In my code I want:

A parent = new A();
parent.addCollection(new B());
parentDao.create(parent)

When Hibernate persit the object it can set a String into A PK and calculate the max + 1 for Inter. Same way for B PK, Hibernate set the same PK value from A (parent => child) and calculate the max + 1 for the second Intenger.

It's possible? Thanks in advance

EDIT

My Class:

Class A {
    static Class A_PK {
      private String codAzienda;
      private Integer year;
      ... Get, Set, HashCode, Equals and toString() ...
    }

   private A_PK id;

   ... another columns ...

   @OneToMany(cascade=ALL)
   @JoinColumns({
      @JoinColumn(name="cod_azienda"),
      @JoinColumn(name="year")
   })
   List<B> children;
}

Class B {
   static Class B_PK {
       private String codAzienda;
       private Integer year;
       private Integer nextId;
       ... Get, Set, HashCode, Equals and toString() ...
   }

 @EmbeddedId
@AttributeOverrides({
   @AttributeOverride(name = "codAzienda", column = @Column(name = "cod_azienda")),
   @AttributeOverride(name = "codCliente", column = @Column(name = "cod_cliente"))
})

   private B_PK id;
   ... another columns ...
}

Upvotes: 0

Views: 4494

Answers (1)

overmeulen
overmeulen

Reputation: 1158

Try the following :

A.java

@Entity
@Table(name = "TABLE_A")
public class A implements Serializable {

    @Id
    @Column(name = "STR_ID")
    private String strId;

    @Id
    @Column(name = "INT_ID")
    @GeneratedValue(strategy = GenerationType.TABLE)
    private Integer intId;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
    private List<B> bs;

    public A(String strId) {
        this.strId = strId;
    }

    public void addB(B b) {
        if (bs == null) {
            bs = new ArrayList<B>();
        }
        b.setA(this);
        bs.add(b);
    }
}

B.java

@Entity
@Table(name = "TABLE_B")
public class B implements Serializable {

    @Id
    @Column(name = "INT_ID")
    @GeneratedValue(strategy = GenerationType.TABLE)
    private Integer intId;

    @Id
    @ManyToOne
    @JoinColumns({
        @JoinColumn(name = "A_STR_FK", referencedColumnName = "STR_ID"),
        @JoinColumn(name = "A_INT_FK", referencedColumnName = "INT_ID")
    })
    private A a;

    void setA(A a) {
        this.a = a;
    }
}

Upvotes: 1

Related Questions