Spring Data JPA Nested Property Query Method

In this tutorial, we will see Spring Data JPA Nested Property Query Method Example using Spring Boot and oracle.

Let’s see how to define the Query method(Query creation from method names) for Nested Property in Spring Data JPA.

Consider we have two entities Student.java and Address.java. Student and Address entities are in one to one relationship and we want to fetch all students from the database who belongs to city pune.

Student.java

package com.netsurfingzone.entity;

@Entity
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

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

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;

	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name = "address_id")
	Address address;

}

 

Address.java

package com.netsurfingzone.entity;

@Entity
public class Address {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "house_number")
	private String houseNumber;
	
	@Column(name = "city")
	private String city;

	
}

 

And we have some record in student and address table as below.

Spring Data JPA Nested Property Query Method Example

 

 

 

Query method to fetch all students who belong to city pune using Spring Data JPA.

List<Student> findByAddressCity(String city);


Generated Query –

Hibernate:
select
address0_.id as id1_0_0_,
address0_.city as city2_0_0_,
address0_.house_number as house_number3_0_0_
from
address address0_
where
address0_.id=?

 

 

Spring Data JPA Nested Property Query Method Example using  Spring Boot and oracle.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – springdatanestedproperty , ArtifactId – springdatanestedproperty and name – springdatanestedproperty) and click on finish. Keep packaging as the jar.

Modify 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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>springdatanestedproperty</groupId>
	<artifactId>springdatanestedproperty</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springdatanestedproperty</name>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>

		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
				</configuration>
			</plugin>


		</plugins>
	</build>
</project>

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

Directory structure –

Spring Data JPA Nested Property Query Method Example

 

Let’s Define entities for Spring Data JPA Nested Property Query Method Example.

Student.java

package com.netsurfingzone.entity;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

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

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;

	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name = "address_id")
	Address address;

	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;
	}

	public String getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(String rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getUniversity() {
		return university;
	}

	public void setUniversity(String university) {
		this.university = university;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

}

Address.java


package com.netsurfingzone.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Address {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "house_number")
	private String houseNumber;
	
	@Column(name = "city")
	private String city;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getHouseNumber() {
		return houseNumber;
	}

	public void setHouseNumber(String houseNumber) {
		this.houseNumber = houseNumber;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}
	
	
}

Let’s Define controller for Spring Data JPA Nested Property Query Method Example.

 

StudentController.java

package com.netsurfingzone.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.netsurfingzone.entity.Student;
import com.netsurfingzone.service.StudentService;

@RestController
@RequestMapping(value = "/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@RequestMapping(value = "/saveall", method = RequestMethod.POST)
	@ResponseBody
	public List<Student> saveAllStudents(@RequestBody List<Student> studentList) {
		List<Student> studentResponse = (List<Student>) studentService.saveAllStudent(studentList);
		return studentResponse;
	}

	@RequestMapping(value = "/address/{city}", method = RequestMethod.GET)
	@ResponseBody
	public List<Student> findByAddressCity(@PathVariable String city) {

		List<Student> studentResponse = (List<Student>) studentService.findByAddressCity(city);
		return studentResponse;
	}
	

}

 

Note – See more details about @Controller and RestController here.

StudentRepository.java – interface

package com.netsurfingzone.repository;

import java.io.Serializable;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.netsurfingzone.entity.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {
	
	List<Student> findByAddressCity(String city);
	


}

StudentService.java – interface

package com.netsurfingzone.service;

import java.util.List;

import org.springframework.stereotype.Component;

import com.netsurfingzone.entity.Student;


@Component
public interface StudentService {
	public List<Student> saveAllStudent(List<Student> studentList);

	List<Student> findByAddressCity(String city);
	

}

Note – See here more about @Component, @Controller, @Service and @Repository annotations here.

StudentServiceImpl.java


package com.netsurfingzone.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.netsurfingzone.entity.Student;
import com.netsurfingzone.repository.StudentRepository;
import com.netsurfingzone.service.StudentService;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@Transactional
	public List<Student> saveAllStudent(List<Student> studentList) {
		List<Student> response = (List<Student>) studentRepository.saveAll(studentList);
		return response;
	}

	@Transactional
	public List<Student> findByAddressCity(String city) {
		List<Student> response = (List<Student>) studentRepository.findByAddressCity(city);
		return response;
	}
	
	
	

	
}

SpringMain.java

package com.netsurfingzone.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.*")
@EntityScan("com.netsurfingzone.entity")
public class SpringMain {
	public static void main(String[] args) {

		SpringApplication.run(SpringMain.class, args);
	}

}

Note – See more details about @ComponentScan here.

JpaConfig.java

package com.netsurfingzone.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "com.netsurfingzone.repository")
public class JpaConfig {

}

Note – See more details about @Configuration annotations here.

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle2
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql=true 
 
spring.jpa.hibernate.ddl-auto =create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091

#show sql values
logging.level.org.hibernate.type.descriptor.sql=trace

#hibernate.show_sql = true
#spring.jpa.hibernate.logging.level.sql =FINE
#show sql statement
#logging.level.org.hibernate.SQL=debug

Let’s run the SpringMain class(run as java application).

Perform saveall operation first using below REST API.

http://localhost:9091/student/saveall

[{
		"name": "john",
		"rollNumber": "120",
		"university": "rgtu",
		"address": {
			"city": "bangalore",
			"houseNumber": "45"
		}
	},
	{
		"name": "mark",
		"rollNumber": "121",
		"university": "rgtu",
		"address": {
			"city": "bangalore",
			"houseNumber": "46"
		}
	},
	{
		"name": "josef",
		"rollNumber": "123",
		"university": "rgtu",
		"address": {
			"city": "pune",
			"houseNumber": "47"
		}
	},
	{
		"name": "hulk",
		"rollNumber": "124",
		"university": "rgtu",
		"address": {
			"city": "pune",
			"houseNumber": "49"
		}
	}
]

 

Response Data.

[
    {
        "id": 1,
        "name": "john",
        "rollNumber": "120",
        "university": "rgtu",
        "address": {
            "id": 2,
            "houseNumber": "45",
            "city": "bangalore"
        }
    },
    {
        "id": 3,
        "name": "mark",
        "rollNumber": "121",
        "university": "rgtu",
        "address": {
            "id": 4,
            "houseNumber": "46",
            "city": "bangalore"
        }
    },
    {
        "id": 5,
        "name": "josef",
        "rollNumber": "123",
        "university": "rgtu",
        "address": {
            "id": 6,
            "houseNumber": "47",
            "city": "pune"
        }
    },
    {
        "id": 7,
        "name": "hulk",
        "rollNumber": "124",
        "university": "rgtu",
        "address": {
            "id": 8,
            "houseNumber": "49",
            "city": "pune"
        }
    }
]

 

http://localhost:9091/student/address/pune

Spring Data JPA Nested Property Query Method Example

That’s all about Spring Data JPA Nested Property Query Method Using Spring Boot and oracle.

 

You may like.

 

Other Spring Data JPA and Hibernate tutorials.

 

Spring Data JPA Docs.