Tuesday, June 11, 2013

08 - Value-Types-and-Embedding-Objects

How would you save an object in database e.g. list, array etc.

In hibernate we see two kind of objects - Entity object and value object

Entity object:  It has an object which is saved as a separate table in database and it is independent. It has value of its own

Value object: it is an object that has a data, but it does not have meaning as of itself it provide meaning to other object e.g. address. It doesn’t have value of its own.

@Embeddable -> Object must be embedded in some other object
@Embedded-> same as Embeddable but it will add at object initialization.

The @Embedded annotation is used to specify the Address entity should be stored in the USER_DETAILS table as a component. @Embeddable annotation is used to specify the Address class will be used as a component. The Address class cannot have a primary key of its own; it uses the enclosing class primary key.




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.setAddress(addr);
            user.setJoinedDate(new Date());
            user.setDescription("Description of user goes here");

            user2.setAddress(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());

      }
}


UserDetails.java

package org.yash.dto;

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_DETAILS")
public class UserDetails {
      /* @Id says "userId" is primary key */
      @Id @GeneratedValue (strategy=GenerationType.AUTO)
      private int userId;    
      private String userName;
      private Address address;
     
      private Date joinedDate;
      private String description;
     
      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 Date getJoinedDate() {
            return joinedDate;
      }
      public void setJoinedDate(Date joinedDate) {
            this.joinedDate = joinedDate;
      }
      public String getDescription() {
            return description;
      }
      public void setDescription(String description) {
            this.description = description;
      }
      public void setAddress(Address address) {
            this.address = address;
      }
      public Address getAddress() {
            return address;
      }
}

Address.java
package org.yash.dto;

import javax.persistence.Embeddable;

@Embeddable
public class Address {
      private String street;
      private String city;
      private String state;
      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;
      }
     
}


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>

        <property name="connection.driver_class">
            org.postgresql.Driver
        </property>
        <property name="connection.url">
            jdbc:postgresql://localhost:5433/hibernatedb
        </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>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
       
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
       
        <!-- Drop and re-create the database schema on startup -->
            <property name="hbm2ddl.auto">create</property> 
<!-- create / update -->
   
          <!-- Names the annotated entity class -->
          <mapping class="org.yash.dto.UserDetails"/>

    </session-factory>

</hibernate-configuration>

No comments:

Post a Comment