Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate, id, oracle, sequence

My database is Oracle, and my id column value is an Oracle sequence, this sequence is executed by a trigger, so, before each row is inserted this trigger use this sequence to get the id value. So I am confused in which id strategy generation should I define in my entity class.

@GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")

or

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "idGenerator")
@SequenceGenerator(name="idGenerator", sequenceName="ID_SEQ")

or

@Id
@GeneratedValue(strategy = GenerationType.AUTO)

Really confused, Could someone shed some light on this subject? Please explain clearly..

like image 474
kneethan Avatar asked Mar 16 '11 19:03

kneethan


Video Answer


1 Answers

I had also a projet where an Oracle DB that provides the data to my @Entity classes. As you said, a sequence generates the id for the PK of the table via a trigger. This was the annotations that I used in one of these classes:

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "G1")
@SequenceGenerator(name = "G1", sequenceName = "LOG_SEQ")
@Column(name = "ID", unique = true, nullable = false, precision = 22, scale = 0)
public int getId() {
    return this.id;
}

This is the second syntax that you have showed in your post. There's no call to the trigger in the Java code because the trigger is managed by the DB. I remember that I had to have the sequence and the trigger at the same time in the DB if I didn't wanted to have problems. The trigger asked if the id of the row to insert is null or = 0. In this case the sequence LOG_SEQ is called.

So if you provide a value to the @Id of your entity it could be inserted in the DB (if that Id doesn't exist) and the sequence would not be called. Try to see the code of the trigger to see exactly what it happens.

like image 79
jomaora Avatar answered Oct 19 '22 08:10

jomaora