Hibernate One-to-one-tutorial Annotations

Click here to download eclipse supported ZIP file




 
<?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.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 
		hibernate word is optional <property name="connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property> 
		<property name="hibernate.connection.username">kcv</property> <property name="hibernate.connection.password">kcv</property> 
		<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> 
		<property name="show_sql">true</property> <mapping resource="Employee.hbm.xml"/> 
		</session-factory> -->
   <session-factory>
      <property name="hibernate.current_session_context_class">thread</property>
      <property name="hbm2ddl.auto">create</property>
      <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
      <property name="connection.url">jdbc:postgresql://localhost:5432/hibernate</property>
      <property name="connection.username">postgres</property>
      <property name="connection.password">password</property>
      <property name="connection.driver_class">org.postgresql.Driver</property>
      <property name="show_sql">true</property>
      <property name="format_sql">true</property>
      <property name="use_sql_comments">true</property>
      		<mapping class="com.cv.hibernate.onetoone.annotation.model.EmployeeDetail" />
   </session-factory>
</hibernate-configuration>


 

    
package com.cv.hibernate.onetoone.annotation.model;

import java.sql.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/** @author Chandra Vardhan */

@Entity
@Table(name="TBL_EMPLOYEE_ANN_ONE_ONE")
public class Employee {

  @Id
  @GeneratedValue
  @Column(name="employee_id")
  private Long employeeId;
  
  @Column(name="firstname")
  private String firstName;;
  
  @Column(name="lastname")
  private String lastName;
  
  @Column(name="birth_date")
  private Date birthDate;
  
  @Column(name="cell_phone")
  private String cellphone;

  @OneToOne(mappedBy="employee", cascade=CascadeType.ALL)
  private EmployeeDetail employeeDetail;
  
  public Employee() {
    
  }
  
  public Employee(String firstname, String lastname, Date birthdate, String phone) {
    this.firstName = firstname;
    this.lastName = lastname;
    this.birthDate = birthdate;
    this.cellphone = phone;
    
  }

  public EmployeeDetail getEmployeeDetail() {
    return employeeDetail;
  }

  public void setEmployeeDetail(EmployeeDetail employeeDetail) {
    this.employeeDetail = employeeDetail;
  }

  public Long getEmployeeId() {
    return employeeId;
  }

  public void setEmployeeId(Long employeeId) {
    this.employeeId = employeeId;
  }

  public String getFirstname() {
    return firstName;
  }

  public String getLastname() {
    return lastName;
  }

  public Date getBirthDate() {
    return birthDate;
  }

  public String getCellphone() {
    return cellphone;
  }

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

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

  public void setBirthDate(Date birthDate) {
    this.birthDate = birthDate;
  }

  public void setCellphone(String cellphone) {
    this.cellphone = cellphone;
  }
  
}


 

    
package com.cv.hibernate.onetoone.annotation.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

/**
 @author Chandra Vardhan
 */
@Entity
@Table(name = "TBL_EMPLOYEEDETAIL_ANN_ONE_ONE")
public class EmployeeDetail {

  @Id
  @Column(name = "employee_id", unique = true, nullable = false)
  @GeneratedValue(generator = "gen")
  @GenericGenerator(name = "gen", strategy = "foreign", parameters = @Parameter(name = "property", value = "employee") )
  private Long employeeId;

  @Column(name = "street")
  private String street;

  @Column(name = "city")
  private String city;

  @Column(name = "state")
  private String state;

  @Column(name = "country")
  private String country;

  @OneToOne
  @PrimaryKeyJoinColumn
  private Employee employee;

  public EmployeeDetail() {

  }

  public EmployeeDetail(String street, String city, String state, String country) {
    this.street = street;
    this.city = city;
    this.state = state;
    this.country = country;
  }

  public Employee getEmployee() {
    return employee;
  }

  public void setEmployee(Employee employee) {
    this.employee = employee;
  }

  public String getStreet() {
    return street;
  }

  public void setStreet(String street) {
    this.street = street;
  }

  public String getCity() {
    return city;
  }

  public void setCity(String city) {
    this.city = city;
  }

  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

  public String getCountry() {
    return country;
  }

  public void setCountry(String country) {
    this.country = country;
  }

  public Long getEmployeeId() {
    return employeeId;
  }

  public void setEmployeeId(Long employeeId) {
    this.employeeId = employeeId;
  }
}


 

    
package com.cv.hibernate.onetoone.annotation;

/** @author Chandra Vardhan */
import java.sql.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import com.cv.hibernate.onetoone.annotation.model.Employee;
import com.cv.hibernate.onetoone.annotation.model.EmployeeDetail;
import com.cv.hibernate.onetoone.annotation.util.HibernateUtil;

public class TestClient {

  private final static Logger logger = Logger.getLogger(TestClient.class);

  public static void main(String[] args) {

    logger.info("Hibernate One-To-One example (Annotation)");

    Session session = HibernateUtil.getSession();
    session.beginTransaction();

    EmployeeDetail employeeDetail = new EmployeeDetail("10th Street""LA""San Francisco""U.S.");

    Employee employee = new Employee("Chandra""Vardhan"new Date(121212)"114-857-965");
    employee.setEmployeeDetail(employeeDetail);
    employeeDetail.setEmployee(employee);

    session.save(employee);

    List<Employee> employees = session.createQuery("from Employee").list();
    for (Employee employee1 : employees) {
      logger.info(employee1.getFirstname() " , " + employee1.getLastname() ", "
          + employee1.getEmployeeDetail().getState());
    }

    session.getTransaction().commit();
    logger.info("Saved successfully...");
    HibernateUtil.closeSession();

  }
}


 

    
package com.cv.hibernate.onetoone.annotation.util;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;


/**
 * Configures and provides access to Hibernate sessions, tied to the current
 * thread of execution. Follows the Thread Local Session pattern, see
 {@link http://hibernate.org/42.html }.
 */
public class HibernateUtil {
  
  private final static Logger logger = Logger.getLogger(HibernateUtil.class);

  /**
   * Location of hibernate.cfg.xml file. Location should be on the classpath
   * as Hibernate uses #resourceAsStream style lookup for its configuration
   * file. The default classpath location of the hibernate config file is in
   * the default package. Use #setConfigFile() to update the location of the
   * configuration file for the current session.
   */
  private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
  private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
  private static Configuration configuration = new Configuration();
  private static SessionFactory sessionFactory;

  static {
    try {
      configuration = configuration.configure(CONFIG_FILE_LOCATION);
      StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
          .applySettings(configuration.getProperties());
      sessionFactory = configuration.buildSessionFactory(builder.build());
      logger.info("%%%% Connection successful %%%%");
    catch (Exception e) {
      logger.error("%%%% Error Creating SessionFactory %%%%");
      e.printStackTrace();
    }
  }

  private HibernateUtil() {
  }

  /**
   * Returns the ThreadLocal Session instance. Lazy initialize the
   <code>SessionFactory</code> if needed.
   *
   @return Session
   @throws HibernateException
   */
  public static Session getSession() throws HibernateException {
    Session session = (SessionthreadLocal.get();

    if (session == null || !session.isOpen()) {
      if (sessionFactory == null) {
        rebuildSessionFactory();
      }
      session = (sessionFactory != null? sessionFactory.openSession() null;
      threadLocal.set(session);
    }

    return session;
  }

  /**
   * Rebuild hibernate session factory
   *
   */
  public static void rebuildSessionFactory() {
    try {
      configuration = configuration.configure(CONFIG_FILE_LOCATION);
      StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
          .applySettings(configuration.getProperties());
      sessionFactory = configuration.buildSessionFactory(builder.build());
      logger.info("%%%% Connection successful %%%%");
    catch (Exception e) {
      logger.error("%%%% Error Creating SessionFactory %%%%");
      e.printStackTrace();
    }
  }

  /**
   * Close the single hibernate session instance.
   *
   @throws HibernateException
   */
  public static void closeSession() throws HibernateException {
    Session session = (SessionthreadLocal.get();
    threadLocal.set(null);

    if (session != null) {
      session.close();
      System.exit(0);
    }
  }

  /**
   * return session factory
   *
   */
  public static SessionFactory getSessionFactory() {
    return sessionFactory;
  }

  /**
   * return hibernate configuration
   *
   */
  public static Configuration getConfiguration() {
    return configuration;
  }
  
}







#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.hibernate.onetoone.annotation</groupId> <artifactId>Hibernate-One-to-one-tutorial-Annotations</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <artifactId>hibernate-core</artifactId> <groupId>org.hibernate</groupId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.2.0.Final</version> </dependency> <dependency> <groupId>org.hibernate.common</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>4.0.4.Final</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> provided </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.4</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.1.0.CR2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.4</version> </dependency> <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.1-901.jdbc4</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>


No comments:

Post a Comment