Friday 21 February 2020

Spring Jpa: Setting default values for columns

Approach 1: Assign default value to the property.
@Column(name = "FIRST_NAME")
private String firstName = "no_name";

In the above snippet, I defined firstName instance variable with value "no_name", if application do not set this field then ‘no_name’ is assigned by default.

Approach 2: Using PrePersist hook.
@PrePersist
void preInsert() {
    if (this.lastName == null) {
        this.lastName = "no_name";
    }
}

Find the below working application.

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

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

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

    @Column(name = "FIRST_NAME")
    private String firstName = "no_name";

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

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

    @PrePersist
    void preInsert() {
        if (this.lastName == null) {
            this.lastName = "no_name";
        }
    }

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

}

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

import org.springframework.data.repository.CrudRepository;

import com.sample.app.entity.Employee;

public interface EmployeeRepository extends CrudRepository<Employee, Integer> {

}

EmployeeService.java
package com.sample.app.service;

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

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

import com.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    public List<Employee> getAllEmployees() {
        List<Employee> emps = new ArrayList<>();
        employeeRepository.findAll().forEach(emps::add);
        return emps;
    }

    public Employee createEmployee(Employee emp) {
        return employeeRepository.save(emp);
    }

}

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 com.sample.app.entity.Employee;
import com.sample.app.service.EmployeeService;

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

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

            Employee emp2 = new Employee();
            emp2.setFirstName("Ram");

            Employee emp3 = new Employee();
            emp3.setLastName("Gurram");

            Employee emp4 = new Employee();
            emp4.setFirstName("Jagan");
            emp4.setLastName("Gummadi");

            employeeService.createEmployee(emp1);
            employeeService.createEmployee(emp2);
            employeeService.createEmployee(emp3);
            employeeService.createEmployee(emp4);

            List<Employee> emps = employeeService.getAllEmployees();

            System.out.println("-------------------------");
            System.out.println("Printing Employees");
            System.out.println("-------------------------");
            for (Employee emp : emps) {
                System.out.println(emp);
            }

        };
    }

}

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

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

    <name>springbootApp</name>
    <url>http://maven.apache.org</url>

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

Total project structure looks like below.
Run App.java, you can see below messages in console.
-------------------------
Printing Employees
-------------------------
Employee [id=1, firstName=no_name, lastName=no_name]
Employee [id=2, firstName=Ram, lastName=no_name]
Employee [id=3, firstName=no_name, lastName=Gurram]
Employee [id=4, firstName=Jagan, lastName=Gummadi]

As you see the console messages, ‘no_name’ is assigned to uninitialized firstName and lastName properties.

You can download complete working application from this link.

Previous                                                    Next                                                    Home

No comments:

Post a Comment