Insert operation in Hibernate

Insert operation in Hibernate :

Here you will see insert operation through annotation  in Hibernate. To create insert operation you have to create following java class.

  • Employee.java
  • HibernateTest.java

Employee.java :


package com.pkjavacode.com;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* @author pradeep
*/
@Entity
@Table(name = "employee")
public class Employee implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "salary")
private Integer salary;

public Employee() {
}

public Employee(Integer id) {
this.id = id;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getSalary() {
return salary;
}

public void setSalary(Integer salary) {
this.salary = salary;
}
}

HibernateTest.java :


package com.pkjavacode.com;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

/**
*
* @author pradeep
*/
public class HibernateTest {

public static void main(String a[]) {

Session s = null;
try {
s = new AnnotationConfiguration().configure().buildSessionFactory().openSession();
Transaction t = s.beginTransaction();
Employee e = new Employee();
e.setName("Pradeep Yadav");
e.setSalary(45000);
s.save(e);
System.out.println("Record inserted successfully!");
t.commit();
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
s.close();
}
}
}

Output :

Hibernate: insert into employee (name, salary) values (?, ?)
Record inserted successfully!

 

Leave a comment