Hibernate One to Many annotation using Named Query - Java @ Desk

Thursday, October 24, 2013

Hibernate One to Many annotation using Named Query

Hibernate One to Many annotation using Named Query In this example, I have OneToMany releationship between two tables without Join table using annotation.
Table 1 - Person
Table 2 - Address

One Person can have multiple address. Relationship between the two tables is Address table has foreign key "personIdFk" which is mapped by "personId" of Person table.

1) Configure the datasource - This is configured in the spring application context xml file. Configure the bean for datasource using class org.springframework.jdbc.datasource.DriverManagerDataSource. The class can be found in jar spring-jdbc-2.0.7.jar
Load Database Configuration from Properties file

 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
 <property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value>  
 </property>  
 <property name="url"><value>jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]</value>  
 </property>  
 <property name="username"><value>[USERNAME]</value></property>  
    <property name="password"><value>[PASSWORD]</value></property>  
 </bean>
Load Database Configuration from Properties file
2) Configure the SessionFactory of hibernate - This is configured in the spring application context xml file. Configure the bean for SessionFactory using class org.springframework.orm.hibernate.LocalSessionFactoryBean. The class can be found in jar spring-hibernate.jar

<!-- Hibernate SessionFactory -->  
 <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">  
 <property name="dataSource"><ref local="dataSource"/></property>  
 <property name="annotatedClasses">  
 <list>  
 <value>com.javacodeimpl.hibernate.entity.Person</value>  
 <value>com.javacodeimpl.hibernate.entity.Address</value>  
 </list>  
 </property>  
 <property name="hibernateProperties">  
 <props>  
 <prop key="hibernate.dialect">net.sf.hibernate.dialect.OracleDialect</prop>  
 </props>  
 </property>  
 </bean>   
3) Create the Person hibernate entity - In this step, create the Person hibernate entity annotated class.
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "Person")
@NamedQueries({ @NamedQuery(name = "getPersonAddress", query = "select t from Person t where t.id=?") })
public class Person {

    @Id
    @Column(name = "personId")
    private String personId;

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

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "person")
    private List
address; public String getPersonId() { return personId; } public void setPersonId(String personId) { this.personId = personId; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } public List
getAddress() { return address; } public void setAddress(List
address) { this.address = address; } }
4) Create the Address hibernate entity - In this step, create the Person hibernate entity annotated class.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "Address")
public class Address {

    @Id
    @Column(name="addressId")
    private String addressId;
    
    @ManyToOne
    @JoinColumn(name = "personIdFk", referencedColumnName = "personId")
    private Person person;

    public String getAddressId() {
        return addressId;
    }

    public void setAddressId(String addressId) {
        this.addressId = addressId;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}
5) OneToMany/ManyToOne Annotation - Person class has @OneToMany annotation means,
One Person can have Many Addresses.

fetch = FetchType.EAGER -> States that when a Person object is loaded, address objects will also gets loaded since the FetchType is EAGER
mappedBy = "person" -> This is mapping between Person and Address class. The Address class must contain field person of type Person.java. Refer to Address.java class above.

Address class has @ManyToOne annotation and @JoinColumn(name = "personIdFk", referencedColumnName = "personId")
@ManyToOne -> Multiple Address has One Person associated with it.
@JoinColumn -> referencedColumnName means column from Person class/table while name refers to column from Address class/table. Values for these fields should match with the Java Field name from classes and not the column names.

6) Load the data
import org.hibernate.Session;
import org.hibernate.Query;
public class Test {

    public static void main(String[] args) {
        Session session = getSession(); // Returns the org.hibernate.Session; Object
        // getPersonAddress Named Query of Person class. Refer to Person.java Named Query Anootation
        Query query = getSession().getNamedQuery("getPersonAddress");
        int personId = 10;
        query.setParameter(0, personId);
        List result=query.list();
        List persons = (List) result;
 if(persons != null) {
  Person person = persons.get(0); // Return the person Object
  List
addresses = person.getAddress(); // Return the Address object for the Person } } }






No comments:

Post a Comment