Followers

hb : Inserting records using hibernate Annotation

hibernet.cfg.xml
=================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="hibernate.connection.url">jdbc:derby://localhost:1527/hari</property>
    <property name="hibernate.connection.username">app</property>
    <property name="hibernate.connection.password">app</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">update</property> 
    <mapping class="mypack.Employee"/>
  </session-factory>
</hibernate-configuration>

Employee.java
===============
package mypack;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "EMP001")
public class Employee {
    @Id
    @Column(name = "ID")
    private int id;
    @Column(name = "FIRST_NAME")
    private String firstName;
    @Column(name = "LAST_NAME")
    private String lastName;

    public int getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

FirsthbAnnotationTest.java
==========================

package mypack;

import java.lang.annotation.Annotation;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
//import org.hibernate.cfg.Configuration;

public class FirsthbAnnotationTest {
    public static void main(String[] args) {
   
    AnnotationConfiguration cfg=new AnnotationConfiguration();  
    cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
    SessionFactory factory=cfg.buildSessionFactory();  
    
   Session session=factory.openSession();  
    Transaction tx = session.beginTransaction();
    Employee emp = new Employee();
   emp.setId(111);
   emp.setFirstName("Mohan1");
   emp.setLastName("Rao1");
   session.persist(emp);
    tx.commit();
    session.close();       
   System.out.println("successfully saved");  
    }
}

No comments:

Post a Comment