Saturday, December 31, 2011

Genetating Primary Key (HIBERNATE Note 2)

Here I am going to note down how to generate primary keys in hibernate.
Q : How do I drop a schema?

AnnotationConfiguration config=new AnnotationConfiguration();
new SchemaExport(config).drop(true, true);

ok lets see how to annotate a class to generate primary keys.

Note : Useful annotations

  • @Table (name="TableName") : Specify a name for the table
  • @Column(name="ColumnName") : Specify a column name
  • @Column(nullable=false) : the specified column cannot be empty
  • @Transient : The relevant attribute is volatile. not persistent
  • @Basic : default annotation. if we don't give annotation. default one become Basic
  • @Temporal(TemporalType.DATE) :  used to annotate date types
  • @Temporal(TemporalType.TIME) : used to annotate time
  • @Temporal(TemporalType.TIMESTAMP) : used to annotate date and time (time stamp)
  • @GeneratedValue : generate values automatically
  • @GeneratedValue(strategy=GenerationType.TABLE, generator="stdId") most DBs support this type. and generate keys in a sequence. SEQUENCE type is not supported by DBDerby.

Important!   : if we use TABLE type as the Generation Type we have to use a special annotation above @GeneratedValue annotation. it is @TableGenerator 
ex :
@GeneratedValue(strategy=GenerationType.TABLE, generator="stdId")

package com.hibernate.ch1;

import java.util.Calendar;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

public class Student {
 private int stdID;
 private String stdName;
 private int stdAge;
 private String passwd;
 private Calendar birthDate;
 private Date loginTime;
 @GeneratedValue(strategy=GenerationType.TABLE, generator="stdId")
 public int getStdID() {
  return stdID;
 public void setStdID(int stdID) {
  this.stdID = stdID;
 public String getStdName() {
  return stdName;
 public void setStdName(String stdName) {
  this.stdName = stdName;
 public int getStdAge() {
  return stdAge;
 public void setStdAge(int stdAge) {
  this.stdAge = stdAge;
 public Calendar getBirthDate() {
  return birthDate;
 public void setBirthDate(Calendar birthDate) {
  this.birthDate = birthDate;
 public Date getLoginTime() {
  return loginTime;
 public void setLoginTime(Date loginTime) {
  this.loginTime = loginTime;
 public String getPasswd() {
  return passwd;
 public void setPasswd(String passwd) {
  this.passwd = passwd;


Post a Comment

© kani.stack.notez 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis