views:

54

answers:

1

Hi,

I want Hibernate 3.3.0 to generate a value by performing a SELECT query before INSERT (persist()). Which would work like this:

@Generated(GenerationTime.INSERT)
@GenerateSQL("SELECT RANDOM() * 2")
private int number;

I've had a look at @Generated(), that's good for TRIGGERs. I don't want to introduce a trigger.

I also looked at @Formula, that's read-only.

So, what's the right combination of annotations? Thanks.

+1  A: 

I want Hibernate 3.3.0 to generate a value by performing a SELECT query before INSERT

I don't think this is supported.

Alternative #1: you could maybe perform the SELECT as part of the "create" logic, directly in your code.

Alternative #2: use an Hibernate Interceptor, provide a reference to the SessionFactory and perform the SELECT during onSave from the Interceptor.

So, what's the right combination of annotations?

Setting defaults is actually not well supported (see HHH-4341) and the easiest solution would be IMO to define a DEFAULT value at the column level. That would be my Alternative #3. Below an example:

@Generated(GenerationTime.INSERT)
@Column(insertable=false, columnDefinition="INT DEFAULT 20") 
private int someNumber;

I don't know if this is an option for you and I'm not sure if using RANDOM() in the DEFAULT would be supported by the database (how could RANDOM() * 2 become an int by the way?).

Pascal Thivent
Ad #1 - Well, I guess I will end up with this. But that needs me to lift the transaction to higher level of abstraction.Ad `RANDOM()` vs. `int` - ok, you got me :) The real use case is generation of invoice numbers which is not simply a sequence (cancelled invoices etc.)
Ondra Žižka
@Ondra I figured it was an example :) but I see. I don't have better suggestions though.
Pascal Thivent