Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 views
in Technique[技术] by (71.8m points)

java - Hibernate sequence on oracle, @GeneratedValue(strategy = GenerationType.AUTO)

I'm usign @GeneratedValue(strategy = GenerationType.AUTO) to generate the ID on my entity.

I don't now how it works, but on my child table, generates ID values, that follow the parent sequence.

//parent table
@Entity
@Table (name = "parent")
public class Parent {

    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    @Column (name = "id")
    private long id;


    @OneToMany (cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
    @JoinColumn (name = "parentId")
    @ForeignKey (name = "FKparent")
    private List<child> child;

}

//child table
@Entity
@Table (name = "child")
public class Child {

    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    @Column (name = "id")
    private long id;
}

The inserted ID values on parent, updates the sequence. The inserted ID values on child, updates the sequence. On the next insert of parent, the sequence... uses values updated by child insertions...

This Annotations, aren't creating two sequences, only one. Is this correct/expected?

I inserted my entities with my DAO service only using entityManager.persist(parent);

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

These Annotations are no creating two sequences, only one. Is this correct/expected?

That's the expected behavior. When using @GeneratedValue(strategy = GenerationType.AUTO), the JPA provider will pick an appropriate strategy for the particular database. In the case of Oracle, this will be SEQUENCE and, since you did not specify anything, Hibernate will use a single global sequence called hibernate_sequence.

Is this correct? Well, I don't know, it depends on your needs. Just in case, the default maximum value for an Oracle sequence is 1E+27, or 1,000,000,000,000,000,000,000,000,000. That's enough for many.

Now, it is possible to use GenerationType.AUTO and still control the name of the sequence when the database uses sequences:

@Id
@GeneratedValue(strategy=GenerationType.AUTO, generator="my_entity_seq_gen")
@SequenceGenerator(name="my_entity_seq_gen", sequenceName="MY_ENTITY_SEQ")
private Long id;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...