One to Many Mapping Examples in Hibernate
Association mappings are one of the key features of JPA and Hibernate.
They model the relationship between two database tables as attributes in your domain model. That allows you to easily navigate the associations in your domain model and JPQL or Criteria queries.
JPA and Hibernate support the same associations as you know from your relational database model. You can use:
1). One-to-One associations,
2). One-to-Many associations and
3). Many-to-Many associations.
In this tutorial, we will see One-to-Many mapping with different approaches.
We have two entities here: Student and Phone.
Hibernate one to many mapping with join table
This approach uses a join table to store the associations between account and employee entities. @JoinTable annotation has been used to make this association.
@Entity@Table(name = "student")
public class Student {
@Id@GeneratedValue@Column(name = "id")
private long studentId;
@Column(name = "name", nullable = false, length = 100)
private String studentName;
@OneToMany(cascade = CascadeType.ALL)@JoinTable(name = "student_phone", joinColumns = {@JoinColumn(name = "student_id")
},
inverseJoinColumns = {@JoinColumn(name = "phone_id")
})
private Set <Phone> studentPhoneNumbers = new HashSet <Phone> (0);
public Student(String studentName, Set < Phone > studentPhoneNumbers) {
this.studentName = studentName;
this.studentPhoneNumbers = studentPhoneNumbers;
}
/*
@Getters
@Setter
*/
}
We have Phone Entity class
@Entity@Table(name = "phone")
public class Phone {
@Id@GeneratedValue@Column(name = "id")
private long phoneId;
@Column(name = "type", nullable = false, length = 10)
private String phoneType;
@Column(name = "number", nullable = false, length = 15)
private String phoneNumber;
public Phone() {}
public Phone(String phoneType, String phoneNumber) {
this.phoneType = phoneType;
this.phoneNumber = phoneNumber;
}
/*
@Getters
@Setter
*/
}
HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch(Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Hibernate configuration
We have available both entities to runtime, we have to add them in hibernate.cfg.xml file.We need to configure only one set of entities in configuration file otherwise unexpected results can occur.
<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/learning</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.bala.onetomany.Student" />
<mapping class="com.bala.onetomany.Phone" />
</session-factory>
</hibernate-configuration>
We have App.java where we will test the relationship
public class App {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Set <Phone& gt phoneNumbers = new HashSet <Phone >();
phoneNumbers.add(new Phone("home", "1111111111"));
phoneNumbers.add(new Phone("office", "2222222222"));
Student student = new Student("bala", phoneNumbers);
session.save(student);
transaction.commit();
} catch(HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
In this article, we have seen One to Many Mapping Examples in Hibernate. All source code in the article can be found in the GitHub repository.
0 Comments
Post a Comment