In this Spring Data JPA One To Many article, we will learn how to achieve One To Many Mapping using Spring Data JPA. In this approach, we will re-use the same two tables which we used in our previous Spring Data JPA One To One Example.
Creating table
Create EMPLOYEE and EMPLOYEE_ADDRESS Tables, simply Copy and Paste the following SQL query in the query editor to get the table created.
CREATE TABLE "EMPLOYEE" ( "EMP_ID" NUMBER(10,0) NOT NULL ENABLE, "NAME" VARCHAR2(255 CHAR), PRIMARY KEY ("EMP_ID") ); CREATE TABLE "EMPLOYEE_ADDRESS" ( "ADDR_ID" NUMBER(10,0) NOT NULL ENABLE, "EMP_ID" NUMBER(10,0) NOT NULL ENABLE, "STREET" VARCHAR2(255 CHAR), "CITY" VARCHAR2(255 CHAR), "STATE" VARCHAR2(255 CHAR), "COUNTRY" VARCHAR2(255 CHAR), PRIMARY KEY ("ADDR_ID"), CONSTRAINT fk_emp FOREIGN KEY ("EMP_ID") REFERENCES EMPLOYEE ("EMP_ID") );
Folder Structure:
- Create a simple Maven Project “SpringDataJPA” and create a package for our source files “com.javainterviewpoint” under src/main/java
- Now add the following dependency in the POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <groupId>com.javainterviewpoint</groupId> <artifactId>SpringJPA</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringJPA Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <hibernate.version>4.2.0.Final</hibernate.version> <spring.version>4.3.5 RELEASE</spring.version> </properties> <dependencies> <!-- DB related dependencies --> <dependency> <groupId>org.hibernate.common</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>4.0.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.1.9.Final</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.12.1.GA</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.11.3.RELEASE</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>11.2.0</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.1.9.Final</version> </dependency> <!-- SPRING --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.2.5.RELEASE</version> </dependency> <!-- CGLIB is required to process @Configuration classes --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <!-- Servlet API and JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.5.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test-mvc</artifactId> <version>1.0.0.M1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>SpringJPA</finalName> </build> </project>
- Create the Java classes Employee.java, Employee_Address.java, EmployeeRepository.java, SaveLogic.java and RetrieveLogic.java under com.javainterviewpoint folder.
- Place the SpringConfig.xml under the src/main/resources directory
Spring Data JPA One To Many Foreign Key Example
Employee.java
Create a new Java file Employee.java under the package com.javainterviewpoint and add the following code
package com.javainterviewpoint; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="EMPLOYEE") public class Employee { @Id @GeneratedValue @Column(name="EMP_ID") private int empId; @Column(name="NAME") private String empName; @OneToMany(fetch = FetchType.EAGER,mappedBy="employee",cascade = CascadeType.ALL) private Set<Employee_Address> employeeAddress; public Employee() { super(); } public Employee(int empId, String empName, Set<Employee_Address> employeeAddress) { super(); this.empId = empId; this.empName = empName; this.employeeAddress = employeeAddress; } public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public Set<Employee_Address> getEmployeeAddress() { return employeeAddress; } public void setEmployeeAddress(Set<Employee_Address> employeeAddress) { this.employeeAddress = employeeAddress; } @Override public String toString() { return "Employee [empId=" + empId + ", empName=" + empName + "]"; } }
Our Employee class is a simple POJO class consisting of the getters and setters for the Employee class properties (id, name, age, dept).
In the POJO class, we have used the below JPA Annotations.
- @Entity – This annotation will mark our Employee class as an Entity Bean.
- @Table – @Table annotation will map our class to the corresponding database table. You can also specify other attributes such as indexes, catalog, schema, uniqueConstraints. The @Table annotation is an optional annotation if this annotation is not provided then the class name will be used as the table name.
- @Id – The @Id annotation marks the particular field as the primary key of the Entity.
- @GeneratedValue – This annotation is used to specify how the primary key should be generated. Here SEQUENCE Strategy will be used as this the default strategy for Oracle
- @OneToMany – We have used the mappedBy attribute – This denotes the property which will be used for mapping purpose, here we have an attribute “employee” so in our Employee_Address class. This is a mandatory annotation.
- @Column – This annotation maps the corresponding fields to their respective columns in the database table.
Employee_Address.java
Create a new Java file Employee_Address.java under the package com.javainterviewpoint and add the following code
package com.javainterviewpoint; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="EMPLOYEE_ADDRESS") public class Employee_Address { @Id @Column(name = "ADDR_ID") @GeneratedValue private int addrId; @Column(name="STREET") private String street; @Column(name="CITY") private String city; @Column(name="STATE") private String state; @Column(name="COUNTRY") private String country; @ManyToOne(cascade= CascadeType.ALL) @JoinColumn(name = "EMP_ID") private Employee employee; public Employee_Address() { super(); } public Employee_Address(int addrId, String street, String city, String state, String country, Employee employee) { super(); this.addrId = addrId; this.street = street; this.city = city; this.state = state; this.country = country; this.employee = employee; } public int getAddrId() { return addrId; } public void setAddrId(int addrId) { this.addrId = addrId; } 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 getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } }
@ManyToOne annotation defines the relationship many to one (One Employee can have many Employee_Address)
@JoinColumn annotation indicates that this entity will act as the owner of the relationship (This table has a column with a foreign key to the referenced table)
SpringConfig.xml
Place the SpringConfig.xml file also under the src/main/resources folder
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx/ http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd"> <context:component-scan base-package="com.javainterviewpoint"></context:component-scan> <jpa:repositories base-package="com.javainterviewpoint" entity-manager-factory-ref="entityManagerFactoryBean"></jpa:repositories> <bean id="saveLogic" class="com.javainterviewpoint.SaveLogic" /> <bean id="retrieveLogic" class="com.javainterviewpoint.RetrieveLogic" /> <!--EntityManagerFactory --> <bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- Now /META-INF/persistence.xml is no longer needed --> <property name="packagesToScan" value="com.javainterviewpoint" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /> </property> <property name="jpaProperties"> <props> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> </props> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@rsh2:40051:mydb" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactoryBean" /> </bean> </beans>
We have defined the below beans in our SpringConfig file.
- dataSource : This bean holds all the database related configurations such as driverClassName, url, username, password.
- entityManagerFactoryBean: This is the important bean where in which we will be passing the datasource reference and set values to the properties jpaVendorAdapter, jpaProperties
- transactionManager: We are using the JpaTransactionManager for managing the transactions for our application, we will be passing the entityManagerFactoryBean reference to it.
EmployeeRepository.java
Our EmployeeRepository interface extends the JpaRepository interface. The JpaRepository interface contains the basic methods for performing CRUD Operations over an entity. Learn more about the list of methods here.
package com.javainterviewpoint; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; public interface EmployeeRepository extends JpaRepository<Employee,Integer> { }
SaveLogic.java
package com.javainterviewpoint; import java.util.HashSet; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Component; @Component public class SaveLogic { private static SaveLogic saveLogic; @Autowired private EmployeeRepository employeeRepository; public static void main( String[] args ) { //Reading the Configuration file ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springConfig.xml"); //Get the SaveLogic bean saveLogic = (SaveLogic)context.getBean("saveLogic"); saveLogic.saveEmployee(); context.close(); } public void saveEmployee() { Employee employee = new Employee(); employee.setEmpName("JIP"); Employee_Address employeeAddress1 = new Employee_Address(); employeeAddress1.setStreet("Street 1"); employeeAddress1.setCity("City 1"); employeeAddress1.setCountry("Country 1"); employeeAddress1.setState("State 1"); employeeAddress1.setEmployee(employee); Employee_Address employeeAddress2 = new Employee_Address(); employeeAddress2.setStreet("Street 2"); employeeAddress2.setCity("City 2"); employeeAddress2.setCountry("Country 2"); employeeAddress2.setState("State 2"); employeeAddress2.setEmployee(employee); Set<Employee_Address> employeeAddressSet = new HashSet(); employeeAddressSet.add(employeeAddress1); employeeAddressSet.add(employeeAddress2); employee.setEmployeeAddress(employeeAddressSet); employeeRepository.save(employee); System.out.println("Employee and Employee Address saved successfully!!"); } }
- In our SaveLogic class, we have read the Configuration file(SpringConfig.xml) and get all the bean definition through ClassPathXmlApplicationContext
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springConfig.xml");
- Get the SaveLogic Class instance by calling the getBean() method over the context created.
saveLogic = (SaveLogic)context.getBean("saveLogic");
- Call the saveEmployee() method
saveLogic.saveEmployee();
- Set the values for the Properties of Employee and Employee_Address class, and call the save() method over the employeeRepository instance passing the employee instance [save() method is already implemented by JpaRepository ]
Console:
INFO: HHH000261: Table found: EMPLOYEE Jun 16, 2017 4:28:34 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000037: Columns: [name, emp_id] Jun 16, 2017 4:28:34 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000108: Foreign keys: [] Jun 16, 2017 4:28:34 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000126: Indexes: [sys_c0015848] Jun 16, 2017 4:28:38 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000261: Table found: EMPLOYEE_ADDRESS Jun 16, 2017 4:28:38 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000037: Columns: [street, emp_id, state, addr_id, country, city] Jun 16, 2017 4:28:38 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000108: Foreign keys: [fk_emp] Jun 16, 2017 4:28:38 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000126: Indexes: [sys_c0015851] Jun 16, 2017 4:28:38 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000232: Schema update complete Employee and Employee Address saved successfully!!
RetrieveLogic.java
package com.javainterviewpoint; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Component; @Component public class RetrieveLogic { private static RetrieveLogic retrieveLogic; @Autowired private EmployeeRepository employeeRepository; public static void main(String[] args) { // Reading the Configuration file ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springConfig.xml"); // Get the RetrieveLogic bean retrieveLogic = (RetrieveLogic) context.getBean("retrieveLogic"); retrieveLogic.retrieveEmployee(); context.close(); } public void retrieveEmployee() { // Get list of all Employee & Employee Address List<Employee> employeeList = employeeRepository.findAll(); // Displaying the Employee details for (Employee employee : employeeList) { System.out.println("*** Employee Details ***"); System.out.println("Employee Id : " + employee.getEmpId()); System.out.println("Employee Name : " + employee.getEmpName()); System.out.println("*** Employee Address Details ***"); Set<Employee_Address> empAddressSet = employee.getEmployeeAddress(); for (Employee_Address employeeAddress : empAddressSet) { System.out.println("Street : " + employeeAddress.getStreet()); System.out.println("City : " + employeeAddress.getCity()); System.out.println("State : " + employeeAddress.getState()); System.out.println("Country : " + employeeAddress.getCountry()); } } } }
- In our RetrieveLogic class, we have read the Configuration file(SpringConfig.xml) and get all the bean definition through ClassPathXmlApplicationContext
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springConfig.xml");
- Get the SaveLogic Class instance by calling the getBean() method over the context created.
retrieveLogic= (retrieveLogic)context.getBean("saveLogic");
- Call the retrieveEmployee() method
retrieveLogic.retrieveEmployee ();
- Call the findAll() method over the employeeRepository instance [findAll() method is already implemented by JpaRepository ]
Output:
*** Employee Details *** Employee Id : 84 Employee Name : JIP *** Employee Address Details *** Street : Street 2 City : City 2 State : State 2 Country : Country 2 Street : Street 1 City : City 1 State : State 1 Country : Country 1
Leave a Reply