@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Why we are using this annotations? i need to know if this autoincrement my table id values. (GenerationType.IDENTITY) is there any other types whats actually happening when we use this annotation
public class Author extends Domain
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "name")
private String name;
@Column(name = "address")
private String address;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "authorId")
private List<Book>
bookList;
public Author()
{
setServiceClassName("wawo.tutorial.service.admin.AuthorService");
}
}
*Is it necessary to extend Domain abstract class?What is the use?
First of all, using annotations as our configure method is just a convenient method instead of coping the endless XML configuration file.
The
@Idannotation is inherited fromjavax.persistence.Id, indicating the member field below is the primary key of current entity. Hence your Hibernate and spring framework as well as you can do somereflectworks based on this annotation. For details, please check javadoc for IdThe
@GeneratedValueannotation is to configure the way of increment of the specified column(field). For example, when usingMysql, you may specifyauto_incrementin the definition of table to make it self-incremental, and then usein the Java code to denote that you also acknowledged to use this database server side strategy. Also, you may change the value in this annotation to fit different requirements.
1. Define Sequence in database
For instance, Oracle has to use
sequenceas increment method, say we create a sequence in Oracle:2. Refer the database sequence
Now that we have the sequence in database, but we need to establish the relation between Java and DB, by using
@SequenceGenerator:sequenceNameis the real name of a sequence in Oracle,nameis what you want to call it in Java. You need to specifysequenceNameif it is different fromname, otherwise just usename. I usually ignoresequenceNameto save my time.3. Use sequence in Java
Finally, it is time to make use this sequence in Java. Just add
@GeneratedValue:The
generatorfield refers to which sequence generator you want to use. Notice it is not the real sequence name in DB, but the name you specified innamefield ofSequenceGenerator.4. Complete
So the complete version should be like this:
Now start using these annotations to make your JavaWeb development easier.