Getting the last inserted record id of a database table in java using hibernate
JavaBean
package auto;
public class User implements java.io.Serializable {
private int uid;
private String uname;
public User() {
}
public User(String uname) {
this.uname = uname;
}
public User(int uid, String uname) {
this.uid = uid;
this.uname = uname;
}
public User(int uid) {
this.uid = uid;
}
public User(int uid, String uname) {
this.uid = uid;
this.uname = uname;
}
public int getUid() {
return this.uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return this.uname;
}
public void setUname(String uname) {
this.uname = uname;
}
}
Mapping File
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 1 May, 2012 5:12:20 PM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="auto.User" table="user" catalog="mydb">
<id name="uid" type="int">
<column name="uid" />
<generator class="increment" />
</id>
<property name="uname" type="string">
<column name="uname" length="20" />
</property>
</class>
</hibernate-mapping>
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SessionFactory sf;
Session s;
Transaction tx;
Configuration cfg=new Configuration().configure();
sf=cfg.buildSessionFactory();
s=sf.openSession();
tx=s.beginTransaction();
User u=new User("ram");
s.save(u);
tx.commit();
s.flush();
System.out.println("Last Generated Id: "+u.getUid());
s.close();
}
}
If suppose that you have a third field in which want to insert alphanumeric value, which is generated by concatenating generated last id;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SessionFactory sf;
Session s;
Transaction tx;
Configuration cfg=new Configuration().configure();
sf=cfg.buildSessionFactory();
s=sf.openSession();
tx=s.beginTransaction();
User u=new User("ram");
s.save(u);
tx.commit();
s.flush();
s.close();
s=sf.openSession();
tx=s.beginTransaction();
u.setId("uoo1"+u.getUid);
s.update(u);
tx.commit();
s.flush();
s.close();
}
}
Note: must be add id field in bean class and mapping for 'id' field in mapping file
No comments:
Post a Comment