2

I have this two classes and I'm trying to perfom a cascade save-update by using hibernate and JPA annotations, but when I try to save my Order object I'm getting an exception described as following:

Here is the Order class

@Entity
@Table(name="orders")
public class Order {

    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    private Integer idOc;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL ,mappedBy = "order")
    @Valid 
    private List<OrderLine> lines = new ArrayList<OrderLine>(Arrays.asList(new OrderLine()));

   // getters and setters
}

And here is my OrderLine class

@Entity
@Table(name="orderLines ")
public class OrderLine {

    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    private Integer idOl;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "idOc")
    private Order order;

    // getters and setters
}

Here are the exceptions I'm getting:

1 - org.hibernate.exception.ConstraintViolationException: could not execute statement.

2 - Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'idOl' cannot be null.

The idOl is supose to be assigned by hibernate generator but somehow it is not working. Any idea?

Update: On console I can see Hibernate is doing the insert on the parent table but when it tries to do the insert on the child table the exception is thrown. I can see Hibernate is not assinging the autoincrement value for every element contained on the List<>, but I can't figure it out why.

Martin
  • 215
  • 5
  • 14
  • Please refer to http://stackoverflow.com/questions/18205574/difference-between-generatedvalue-and-genericgenerator – nayakam Feb 13 '15 at 03:10
  • Define @column as not null-able and try – nayakam Feb 13 '15 at 03:44
  • Is it ok to have space in order line table definition. @Table(name="orderLines ") – nayakam Feb 13 '15 at 03:52
  • @Wall-E Sorry about that, I'm from Argentina and the code is in spanish. When I was translating it to make it more easy to read I made that error but the original doesn't has that space. – Martin Feb 13 '15 at 11:58

1 Answers1

0

I rely on a real DB sequence object. e.g. define the following at class level:

@SequenceGenerator(
    name="SEQ_ORDER",sequenceName="SEQ_ORDER", allocationSize=1, initialValue=1)

And then use the same sequence in the GeneratedValue attribute of Id field. e.g

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_ORDER")
@Column(name="ID", nullable=false)
protected Integer id;
Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
Maverik
  • 47
  • 4