In this Spring Data JPA One To One article, we will learn how to achieve One To One Mapping using Spring Data JPA. In this approach, we will have two tables with different primary keys. The primary key of EMPLOYEE table (EMP_ID) will act as a foreign key for the EMPLOYEE_ADDRESS table and EMPLOYEE_ADDRESS table will have its own primary key (ADDR_ID).
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 One 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 javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; 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; @OneToOne(mappedBy="employee") private Employee_Address employeeAddress; public Employee() { super(); } public Employee(int empId, String empName, 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 Employee_Address getEmployeeAddress() { return employeeAddress; } public void setEmployeeAddress(Employee_Address employeeAddress) { this.employeeAddress = employeeAddress; } @Override public String toString() { return "Employee [empId=" + empId + ", empName=" + empName + ", employeeAddress=" + employeeAddress + "]"; } }
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
- @OneToOne – This annotation on the employeeAddress property of the Employee class indicates that there exist one to one association between Employee_Address Entity. We have also used the mappedBy attribute as “employee” this indicates that this side is not the owner of the relationship.
- @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.OneToOne; 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; @OneToOne(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; } }
@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_Address,Integer> { }
SaveLogic.java
package com.javainterviewpoint; 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 employeeAddress = new Employee_Address(); employeeAddress.setStreet("Street 1"); employeeAddress.setCity("City 1"); employeeAddress.setCountry("Country 1"); employeeAddress.setState("State 1"); employee.setEmployeeAddress(employeeAddress); employeeAddress.setEmployee(employee); employeeRepository.save(employeeAddress); 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 employeeAddress [save() method is already implemented by JpaRepository ]
Console:
INFO: HHH000261: Table found: EMPLOYEE Jun 09, 2017 6:00:24 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000037: Columns: [name, emp_id] Jun 09, 2017 6:00:24 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000108: Foreign keys: [] Jun 09, 2017 6:00:24 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000126: Indexes: [sys_c0015848] Jun 09, 2017 6:00:27 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000261: Table found: EMPLOYEE_ADDRESS Jun 09, 2017 6:00:27 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000037: Columns: [street, emp_id, state, addr_id, country, city] Jun 09, 2017 6:00:27 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000108: Foreign keys: [fk_emp] Jun 09, 2017 6:00:27 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: HHH000126: Indexes: [sys_c0015851] Jun 09, 2017 6:00:27 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 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 empAddress = employeeRepository.findAll(); // Displaying the Employee details for (Employee_Address employeeAddress : empAddress) { System.out.println("*** Employee Details ***"); Employee employee = employeeAddress.getEmployee(); System.out.println("Employee Id : " + employee.getEmpId()); System.out.println("Employee Name : " + employee.getEmpName()); System.out.println("*** Employee Address Details ***"); 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 : 80 Employee Name : JIP *** Employee Address Details *** Street : Street 1 City : City 1 State : State 1 Country : Country 1
Leave a Reply