Tuesday, 27 August 2019

Spring Data JPA: Project data to new model

Step 1: Create a new model class that contains all the properties that you are interested in.
public class EmployeeDetails {
    private int empId;
    private String name;
    private String country;

    .....
    .....
}

Step 2: Add public constructor to EmployeeDetails class.
public class EmployeeDetails {
    private int empId;
    private String name;
    private String country;

    public EmployeeDetails(int id, String name, String country) {
        this.empId = id;
        this.name = name;
        this.country = country;
    }
    .....
    .....
}

Step 3: Create a query method in repository interface that matches to list of EmployeeDetails.
@Query("SELECT new com.sample.app.model.EmployeeDetails(e.id,e.firstName,a.country) from Employee e,Address a ")
List<EmployeeDetails> getEmployeeDetails();

Find the below working application.

Employee.java
package com.sample.app.model;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.JoinColumn;

@Entity
public class Employee {
    @Id
    @GeneratedValue
    private int id;
    private String firstName;
    private String lastName;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "emp_address_mapping", joinColumns = @JoinColumn(name = "emp_id"), inverseJoinColumns = @JoinColumn(name = "address_id"))
    List<Address> addresses = new ArrayList<Address>();

    public int getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public List<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
                .append(lastName).append(", addresses=").append(addresses).append("]");
        return builder.toString();
    }

}

Address.java
package com.sample.app.model;

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

@Entity
public class Address {
    @Id
    @GeneratedValue
    private int id;
    private String street;
    private String city;
    private String state;
    private String PIN;
    private String country;

    public int getId() {
        return id;
    }

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

    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 getPIN() {
        return PIN;
    }

    public void setPIN(String pIN) {
        PIN = pIN;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Address [id=").append(id).append(", street=").append(street).append(", city=").append(city)
                .append(", state=").append(state).append(", PIN=").append(PIN).append(", country=").append(country)
                .append("]");
        return builder.toString();
    }

}

EmployeeDetails.java
package com.sample.app.model;

public class EmployeeDetails {
    private int empId;
    private String name;
    private String country;

    public EmployeeDetails(int id, String name, String country) {
        this.empId = id;
        this.name = name;
        this.country = country;
    }

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("EmployeeDetails [empId=").append(empId).append(", name=").append(name).append(", country=")
                .append(country).append("]");
        return builder.toString();
    }

}

AddressRepository.java
package com.sample.app.repository;

import org.springframework.data.repository.CrudRepository;

import com.sample.app.model.Address;

public interface AddressRepository  extends CrudRepository<Address, Integer>{

}

EmployeeRepository.java
package com.sample.app.repository;

import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import com.sample.app.model.Employee;
import com.sample.app.model.EmployeeDetails;

public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
    @Query("SELECT new com.sample.app.model.EmployeeDetails(e.id,e.firstName,a.country) from Employee e,Address a ")
    List<EmployeeDetails> getEmployeeDetails();
}

App.java
package com.sample.app;

import java.util.List;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import com.sample.app.model.Address;
import com.sample.app.model.Employee;
import com.sample.app.model.EmployeeDetails;
import com.sample.app.repository.EmployeeRepository;

@SpringBootApplication
@EnableJpaAuditing
public class App {

    public static void main(String args[]) {
        SpringApplication.run(App.class, args);
    }

    @Bean
    public CommandLineRunner demo(EmployeeRepository employeeRepository) {
        return (args) -> {
            Employee emp1 = new Employee();

            emp1.setFirstName("Hari Krishna");
            emp1.setLastName("Gurram");

            Address addr1 = new Address();
            addr1.setCity("Bangalore");
            addr1.setCountry("India");
            addr1.setPIN("560037");
            addr1.setState("Karnataka");
            addr1.setStreet("Chowdeswari street");

            Address addr2 = new Address();
            addr2.setCity("Ongole");
            addr2.setCountry("India");
            addr2.setPIN("523169");
            addr2.setState("Andhra Pradesh");
            addr2.setStreet("bodhavada");

            emp1.getAddresses().add(addr1);
            emp1.getAddresses().add(addr2);

            employeeRepository.save(emp1);

            Iterable<Employee> emps = employeeRepository.findAll();

            for (Employee emp : emps) {
                System.out.println(emp);
            }
            
            List<EmployeeDetails> empDetails = employeeRepository.getEmployeeDetails();
            for(EmployeeDetails empDetail : empDetails) {
                System.out.println(empDetail);
            }
            
        };
    }

}

Create application.properties file under src/main/resources folder.

application.properties    
logging.level.root=WARN
logging.level.org.hibernate=ERROR

## H2 specific properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;

spring.datasource.username=krishna
spring.datasource.password=password123

spring.datasource.driverClassName=org.h2.Driver

## JPA specific properties
# Creates the schema, destroying previous data.
spring.jpa.hibernate.ddl-auto=create

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

#spring.jpa.show-sql=true
#spring.jpa.properties.hibernate.format_sql=true

## Database connection pooling properties
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=10
spring.datasource.tomcat.max-idle=5
spring.datasource.tomcat.min-idle=3

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

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>springJPA</groupId>
    <artifactId>springJPA</artifactId>
    <version>1</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>



    <dependencies>


        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>


        <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>


    </dependencies>

</project>

Complete working application looks like below.


Run App.java, you can see below messages in the console.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

Employee [id=1, firstName=Hari Krishna, lastName=Gurram, addresses=[Address [id=2, street=Chowdeswari street, city=Bangalore, state=Karnataka, PIN=560037, country=India], Address [id=3, street=bodhavada, city=Ongole, state=Andhra Pradesh, PIN=523169, country=India]]]
EmployeeDetails [empId=1, name=Hari Krishna, country=India]
EmployeeDetails [empId=1, name=Hari Krishna, country=India]

You can download the complete working application from this link.
    

Previous                                                    Next                                                    Home

No comments:

Post a Comment