Tuesday, June 11, 2013

09 - AttributeOverrides-and-Embedded-Object-Keys



Suppose we have two addresses one is home and another one is office address, In this scenario table column names should be different for home and office addresses, we can override the table column name using annotation @AttributeOverrides.
@AttributeOverrides({
                @AttributeOverride(name="street", column=@Column(name="HOME_STREET_NAME")),
                @AttributeOverride(name="city", column=@Column(name="HOME_CITY_NAME")),
                @AttributeOverride(name="state", column=@Column(name="HOME_STATE_NAME")),
                @AttributeOverride(name="pincode", column=@Column(name="HOME_PIN_CODE")),
})
@EmbeddedId: It is used when you want to use an object as primary key instead of @Id and that object is the combination of all member variables and it should be unique.
Eg:
@EmbeddedID
private LoginUser userId;
Above annotation are used to override column names in database.

UserDetails.java


package org.yash.dto;

import javax.persistence.AttributeOverrides;
import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/* By adding "@Entity" we are telling Hibernate that it is Entity class*/
@Entity
@Table(name="USER_DETAILS")
public class UserDetails {
      /*
       @EmbeddedId
       * */
     
      /* @Id says "userId" is primary key */
      @Id @GeneratedValue (strategy=GenerationType.AUTO)
      private int userId;    
      private String userName;

      /*Used to override the tabel column names*/
      @Embedded  
      @AttributeOverrides({
            @AttributeOverride(name="street",
 column=@Column(name="HOME_STREET_NAME")),
            @AttributeOverride(name="city",
                               column=@Column(name="HOME_CITY_NAME")),
            @AttributeOverride(name="state",
                               column=@Column(name="HOME_STATE_NAME")),
            @AttributeOverride(name="pincode",
 column=@Column(name="HOME_PIN_CODE")),
      })
      private Address homeAddress;
     
      @Embedded
      private Address officeAddress;

      public int getUserId() {
            return userId;
      }
      public void setUserId(int userId) {
            this.userId = userId;
      }
      public String getUserName() {
            return userName;
      }
      public void setUserName(String userName) {
            this.userName = userName;
      }
      public void setHomeAddress(Address homeAddress) {
            this.homeAddress = homeAddress;
      }
      public Address getHomeAddress() {
            return homeAddress;
      }
      public void setOfficeAddress(Address officeAddress) {
            this.officeAddress = officeAddress;
      }
      public Address getOfficeAddress() {
            return officeAddress;
      }
     
}


Address.java
package org.yash.dto;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class Address {
      @Column(name="STREET_NAME")
      private String street;
      @Column(name="CITY_NAME")
      private String city;
      @Column(name="STATE_NAME")
      private String state;
      @Column(name="PIN_CODE")
      private String pincode;
     
      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 getPincode() {
            return pincode;
      }
      public void setPincode(String pincode) {
            this.pincode = pincode;
      }
     
}


HibernateTest.java
package org.yash.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.yash.dto.Address;
import org.yash.dto.UserDetails;

public class HibernateTest {

      public static void main(String args[]){
            UserDetails user = new UserDetails();
            user.setUserName("First User");

            UserDetails user2 = new UserDetails();
            user2.setUserName("Second User");
           
            Address addr = new Address();
            addr.setCity("Bentonville");
            addr.setPincode("72712");
            addr.setState("Ar");
            addr.setStreet("2301 SE Saint Andrews");
           
            user.setHomeAddress(addr);
            user.setOfficeAddress(addr);
            user.setJoinedDate(new Date());
            user.setDescription("Description of user goes here");

           
            user2.setHomeAddress(addr);
            user2.setOfficeAddress(addr);
            user2.setJoinedDate(new Date());
            user2.setDescription("Description of user goes here");     
           
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();         
            Session session = sessionFactory.openSession();
            /* It is used to save all the objects and to define single unit of work */
            session.beginTransaction();
           
            session.save(user);
            session.save(user2);
            session.getTransaction().commit();
           
            user = null;
           
            session = sessionFactory.openSession();
            session.beginTransaction();
            user = (UserDetails) session.get(UserDetails.class, 1);
            System.out.println("User name retrieved is "+user.getUserName());

      }
}


hibernate.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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">
org.postgresql.Driver
  </property>
        <property name="connection.url">
jdbc:postgresql://localhost:5432/hibernated
  </property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">admin</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">
            org.hibernate.dialect.PostgreSQLDialect
        </property>

            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>


            <!-- Drop and re-create the databse schema on startup -->
            <!--<property name="hbm2ddl.auto">create</property>-->
            <property name="hbm2ddl.auto">create</property>
           
            <!-- Names the annotated entity class -->
            <mapping class="org.yash.dto.UserDetails"/>    



    </session-factory>

</hibernate-configuration>

No comments:

Post a Comment