Thursday, 25 December 2014

Change column names of embedded object


An embedded object is one, which is embedded in another object. Let’s say I had Employee class, and two address references one for permanent address, and another for temporary address.

How do I differentiate these two addresses?
You can override the column names of embedded object using @AttributeOverrides annotation.

@Embedded
@AttributeOverrides({
  @AttributeOverride(name="street", column=@Column(name="p_street")),
  @AttributeOverride(name="city", column=@Column(name="p_city")),
  @AttributeOverride(name="state", column=@Column(name="p_state")),
  @AttributeOverride(name="PIN", column=@Column(name="p_PIN")),
  @AttributeOverride(name="country", column=@Column(name="p_country"))
})
private Address permAddress;


@AttributeOverride annotation is used to override single field name.
@AttributeOverrides annotation is used to group all @AttributeOverride annotations.
  
package myFirstHibernate;

public class Address {
  private String street;
  private String city;
  private String state;
  private String PIN;
  private String country;
  
  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 getPIN() {
    return PIN;
  }
  
  public void setPIN(String pIN) {
    PIN = pIN;
  }
  
  public String getCountry() {
    return country;
  }
  
  public void setCountry(String country) {
    this.country = country;
  }
  
}

package myFirstHibernate;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Column;


@Entity
public class Employee {
  @Id
  private int id;
  
  private String firstName;
  private String lastName;
  
  @Embedded
  @AttributeOverrides({
    @AttributeOverride(name="street", column=@Column(name="p_street")),
    @AttributeOverride(name="city", column=@Column(name="p_city")),
    @AttributeOverride(name="state", column=@Column(name="p_state")),
    @AttributeOverride(name="PIN", column=@Column(name="p_PIN")),
    @AttributeOverride(name="country", column=@Column(name="p_country"))
  })
  private Address permAddress;
  
  @Embedded
  private Address tempAddress;
  
  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;
  }
  
  public Address getPermAddress() {
    return permAddress;
  }
  
  public void setPermAddress(Address permAddress) {
    this.permAddress = permAddress;
  }
  
  public Address getTempAddress() {
    return tempAddress;
  }
  
  public void setTempAddress(Address tempAddress) {
    this.tempAddress = tempAddress;
  }
    
}


hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

  <session-factory>
  
    <!--  Database Connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost/sample</property>
    <property name="connection.username">root</property>
    <property name="connection.password">tiger</property>
    
    <!-- Enable the logging of all the generated SQL statements to the console -->
    <property name="show_sql">true</property>
    
    <!-- Format the generated SQL statement to make it more readable, -->
    <property name="format_sql">false</property>
    
    <!-- Hibernate will put comments inside all generated SQL statements to hint what’s the generated SQL trying to do -->
    <property name="use_sql_comments">false</property>
    
    <!-- This property makes Hibernate generate the appropriate SQL for the chosen database. -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    
    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>
    
    <!-- mappings for annotated classes -->
    <mapping class="myFirstHibernate.Employee" />
    
  </session-factory>
  
</hibernate-configuration>

package myFirstHibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class TestEmployee {
  
  /* Step 1: Create session factory */
  private static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
    applySettings(configuration.getProperties());
    SessionFactory factory = configuration.buildSessionFactory(builder.build());
        return factory;
    }
  
  public static void main(String args[]){
    Employee emp1 = new Employee();
    emp1.setId(1);
    emp1.setFirstName("Hari Krishna");
    emp1.setLastName("Gurram");
    
    Address tempAddr = new Address();
    tempAddr.setCity("Bangalore");
    tempAddr.setCountry("India");
    tempAddr.setPIN("560037");
    tempAddr.setState("Karnataka");
    tempAddr.setStreet("Chowdeswari street");
    
    Address permAddr = new Address();
    permAddr.setCity("Ongole");
    permAddr.setCountry("India");
    permAddr.setPIN("523169");
    permAddr.setState("Andhra Pradesh");
    permAddr.setStreet("Punuru");

    emp1.setTempAddress(tempAddr);
    emp1.setPermAddress(permAddr);
    
    /* To persisit data */
    SessionFactory sessionFactory = getSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(emp1);
    session.getTransaction().commit();
    session.close();   
  }
}


Run TestEmployee class, you will get output like below.

Hibernate: drop table if exists Employee
Hibernate: create table Employee (id integer not null, firstName varchar(255), lastName varchar(255), p_PIN varchar(255), p_city varchar(255), p_country varchar(255), p_state varchar(255), p_street varchar(255), PIN varchar(255), city varchar(255), country varchar(255), state varchar(255), street varchar(255), primary key (id))
Dec 20, 2014 10:21:27 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Employee (firstName, lastName, p_PIN, p_city, p_country, p_state, p_street, PIN, city, country, state, street, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)


MySQL structure looks like below.

mysql> select * from employee;
+----+--------------+----------+--------+--------+-----------+----------------+----------+--------+-----------+---------+-----------+--------------------+
| id | firstName    | lastName | p_PIN  | p_city | p_country | p_state        | p_street | PIN    | city      | country | state     | street             |
+----+--------------+----------+--------+--------+-----------+----------------+----------+--------+-----------+---------+-----------+--------------------+
|  1 | Hari Krishna | Gurram   | 523169 | Ongole | India     | Andhra Pradesh | Punuru   | 560037 | Bangalore | India   | Karnataka | Chowdeswari street |
+----+--------------+----------+--------+--------+-----------+----------------+----------+--------+-----------+---------+-----------+--------------------+
1 row in set (0.00 sec)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment