Hibernate - SPLessons

Hibernate Many to One

Home > Lesson > Chapter 25
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Hibernate Many to One

Hibernate Many to One

shape Description

Hibernate Many to One, if the child class object is loaded from the database, Then automatically parent class object also loaded into the database. In Many-to-One Relationship, a parent class object will be set to the multiple objects of the child class. When creating a child POJO class, create a reference variable of type parent class in the child POJO class.

shape Example

In this example, take the details of a Person containing multiple card details like Adharcard and voterId card. let's make the Parent class as Person and child class as CardDetails.
  • Create the project directory structure.
  • Create the persistence classes.
Person.java [java]package com.itoolsinfo; public class Person { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } [/java] Here created the class Person with the variables id and name, set and get methods are performed on this variables. Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, one can define get methods to access these variables, and set methods to modify them. CardDetails.java [java]package com.itoolsinfo; public class CardDetails { private int id; private String cardName; private Person person; public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } } [/java] Hibernate Many to One, Here created the class CardDetails with the variables id, cardName, person. Set and Get operations have performed on this variables.
  • Map the persistence classes in mapping file.
person.hbm.xml [xml] <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”> <hibernate-mapping> <class name=”com.itoolsinfo.Person” table=”person”> <generator class=”native”/> </id> <property name=”name” /> </class> </hibernate-mapping> [/xml] The generator classs ubelement of id utilized to produce the unique identifier for the objects of persistence class. There are numerous generator classes characterized in the Hibernate Framework. All the generator classes actualizes the org.hibernate.id.IdentifierGenerator interface. Generator class native uses identity, sequence or hilo depending on the database vendor. carddetails.hbm.xml [xml] <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.itoolsinfo.CardDetails" table="carddetails"> <id name="id"> <generator class="native"/> </id> <property name="cardName" /> <many-to-one name="person" class="com.itoolsinfo.Person" column="cid" cascade="all"/> </class> </hibernate-mapping> [/xml] The generator class subelement of id utilized to produce the unique identifier for the objects of persistence class. There are numerous generator classes characterized in the Hibernate Framework. All the generator classes actualizes the org.hibernate.id.IdentifierGenerator interface.
  • Configure the mapping files in Configuration file.
hibernate.cfg.xml [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">oracle.jdbc.driver.OracleDriver</property> <property name=>connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="show_sql">true</property> <mapping resource="carddetails.hbm.xml"/> <mapping resource="person.hbm.xml"/> </session-factory> </hibernate-configuration> [/xml]
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
  • Create the SPLessons class and store the POJO class objects to perform the database operations.
SPLessons.java [java]package com.itoolsinfo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session=factory.openSession(); Person person=new Person(); person.setName(" john "); CardDetails carddetails=new CardDetails(); carddetails.setCardName("AadharCard"); carddetails.setPerson(person); CardDetails carddetails2=new CardDetails(); carddetails2.setCardName("voterId"); carddetails2.setPerson(person); Transaction transaction=session.beginTransaction(); session.save(carddetails); session.save(carddetails2); transaction.commit(); session.close(); } } [/java] Output: See the Output in command prompt. See the Output in Database table using following command. [sql]select * from person;[/sql] [sql]select * from carddetails[/sql]
In Many-to-One annotation, one have to use the @manyToOne(cascade=CascadeType.ALL) annotation.
  • Create the project directory structure.
  • Create the persistance classes.
Person.java [java]package com.itoolsinfo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="person") public class Person { @Id @GeneratedValue private int id; @Column(name="name") private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } [/java] The @Table comment permits you to indicate the points of interest of the table that will be utilized to hold on the element in the database. The @Table explanation gives four traits, permitting you to abrogate the name of the table, its inventory, and its composition, and uphold exceptional imperatives on sections in the table. Every element bean will have an essential key, which you comment on the class with the @Id comment. The essential key can be a solitary field or a mix of different fields relying upon your table structure. As a matter of course, the @Id comment will naturally decide the most suitable essential key era technique to be utilized however you can abrogate this by applying the @GeneratedValue explanation which takes two parameters system and generator.
  • Configure the persistence classes in Configuration file.
hibernate.cfg.xml [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=”hibernate.hbm2ddl.auto”>update</property> <property name=”dialect”>org.hibernate.dialect.Oracle10gDialect</property> <property name=”connection.url”<jdbc:oracle:thin:@localhost:1521:XE&lt;/property> <!-- property name=”connection.url”>jdbc:oracle:thin:@127.0.0.1:1521:XE</property <property name=”connection.username”>system</property> <property name=”connection.password”>system</property> <property name=”connection.driver_class&quot;>oracle.jdbc.driver.OracleDriver</property> <mapping class=”com.itoolsinfo.CardDetails”/> <mapping class=”com.itoolsinfo.Person”/> </session-factory” </hibernate-configuration> [/xml]
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
  • Create the SPLessons class and store Persistence class objects to perform the database operations.
SPLessons.java [java]package com.itoolsinfo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session=factory.openSession(); Person person=new Person(); person.setName(" jhon "); CardDetails carddetails=new CardDetails(); carddetails.setCardName("AdharCard"); carddetails.setPerson(person); CardDetails carddetails2=new CardDetails(); carddetails2.setCardName("voterId"); carddetails2.setPerson(person); Transaction transaction=session.beginTransaction(); session.save(carddetails); session.save(carddetails2); transaction.commit(); session.close(); } } [/java] In this class database operations will be performed. Application acquires session objects from Session Factory. SessionFactory is for the most part arranged as Singleton in application, SessionFactory stores produce SQL statements and other mapping metadata that Hibernate utilizes at runtime. Output: See the output in command prompt. See the output in Database table using the following command. [sql]select * from person;[/sql] [sql]select * from carddetails[/sql]

Summary

shape Key Points

  • Hibernate Many to One - lazy attribute is utilized in Many-to-One relationship.
  • lazy attribute either may be proxy or false.
  • If lazy attribute is false then child object is loaded, immediately  parent object will also be loaded from the database.
  • Hibernate Many to One - If lazy attribute is proxy then parent object will not be loaded immediately.