Thursday, 29 April 2021

Spring jpa: @Param Named parameters: bind method parameter to the query

@Param annotation is used to give a method parameter a concrete name and bind the name in the query.

 

Example

@Query("SELECT e FROM Employee e WHERE e.firstName = :fName OR e.lastName = :lName")
public List<Employee> getEmployeesByFirstNameOrLastName(@Param("fName") String firstName, @Param("lName") String lastName);

 

Value of ‘firstName’ is replaced at :fName and value of lastName is replaced at :lName.

 

Find the below working application.

 

Step 1: Create new maven project ‘named-parameter-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>named-parameter-demo</artifactId>
  <version>1</version>

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

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


  <dependencies>

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


    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>


  </dependencies>
</project>

 

Step 3: Create application.properties file in 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=false
spring.jpa.properties.hibernate.format_sql=false

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

 

Step 4: Define Employee entity class.

 

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.Table;

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

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

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

  @Column(name = "age")
  private int age;

  @Column(name = "salary")
  private double salary;

  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 int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public double getSalary() {
    return salary;
  }

  public void setSalary(double salary) {
    this.salary = salary;
  }

  public static EmployeeBuilder builder() {
    return new EmployeeBuilder();
  }

  public static class EmployeeBuilder {
    private Employee emp;

    public EmployeeBuilder() {
      emp = new Employee();
    }

    public EmployeeBuilder firstName(String firstName) {
      emp.setFirstName(firstName);
      return this;
    }

    public EmployeeBuilder lastName(String lastName) {
      emp.setLastName(lastName);
      return this;
    }

    public EmployeeBuilder age(int age) {
      emp.setAge(age);
      return this;
    }

    public EmployeeBuilder salary(double salary) {
      emp.setSalary(salary);
      return this;
    }

    public Employee build() {
      return emp;
    }
  }

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

}

 

Step 5: Define EmployeeRepository interface.

 

EmployeeRepository.java

package com.sample.app.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.sample.app.entity.Employee;

public interface EmployeeRepository extends JpaRepository<Employee, Integer> {

  @Query("SELECT e FROM Employee e WHERE e.firstName = :fName OR e.lastName = :lName")
  public List<Employee> getEmployeesByFirstNameOrLastName(@Param("fName") String firstName,
      @Param("lName") String lastName);
}

 

Step 6: Define main application class.

 

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.repository.EmployeeRepository;

@SpringBootApplication
public class App {

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

  public void printEmployees(Iterable<Employee> emps, String msg) {
    System.out.println(msg);
    for (Employee emp : emps) {
      System.out.println(emp);
    }

    System.out.println();
  }

  @Bean
  public CommandLineRunner demo(EmployeeRepository employeeRepository) {
    return (args) -> {
      Employee emp1 = Employee.builder().firstName("Ram").lastName("Gurram").age(32).salary(100000.23).build();
      Employee emp2 = Employee.builder().firstName("Ram").lastName("Chelli").age(43).salary(60000).build();
      Employee emp3 = Employee.builder().firstName("Gopi").lastName("Battu").age(45).salary(1000000).build();
      Employee emp4 = Employee.builder().firstName("Ram").lastName("Srikanth").age(39).salary(60000).build();
      Employee emp5 = Employee.builder().firstName("Surendra").lastName("Sami").age(32).salary(100000.23).build();

      employeeRepository.save(emp1);
      employeeRepository.save(emp2);
      employeeRepository.save(emp3);
      employeeRepository.save(emp4);
      employeeRepository.save(emp5);

      List<Employee> emps = employeeRepository.getEmployeesByFirstNameOrLastName("Ram", "Sami");
      printEmployees(emps, "All the employees whose firstName is 'Ram' or lastName is 'Sami'");

    };
  }

}

 

Total project structure looks like below.

 


 

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/jpa/named-parameter-demo

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Php: Classes and objects

 

Classes are used to group functions and variables in a single unit. Once you define a class, you can instantiate any number of objects from that class.

 

Objects and class in Real World scenario

 

Object

An Object is a real world entity. For example, book, cat, box, bus, keyboard, person, screen, cell phone etc., all are objects.

 

So How can we differentiate objects

1.   Depend on their properties

2.   Depend on their behaviors

 

Differentiating two objects based on their properties

Let’s say, there are two persons A and B, we already discussed, each real time entity is an object. So these two persons are objects.

 

First let’s try to find what are the possible properties for the person object

 

Possible properties of a person

height, weight, colour, Education Qualification, country, address are all come under person properties.

 

Now by comparing these properties we can easily differentiate two persons.

Properties

Person A

Person B

Height

6ft

5.5ft

Weight

75Kg

60Kg

Color

white

Black

Country

India

America

As shown in the above table, both the persons has their own properties, So we can differentiate based on them.

 

Differentiating two objects based on their behaviour

consider the same two persons A and B. will try to figure out possible behaviours for the person object

 

Possible behaviours are

walk, run, swim, eat, sleep, see, hear etc., Now by comparing these behaviors we can easily differentiate two persons. 

Behavior

Person A

Person B

Walk

10km/hr

12km/hr

run

20km/hr

18km/hr

sleep

8 Hrs/day

6Hrs/day

 

Class

In normal terms I call class as a category.

 

All persons come under Human category

cat, lion, Elephant come under Animals Category

 

So a class or category is a group of objects with similar properties and behaviours.

 

Objects and class in Programming Terminology

 

What Is an Object?

An object is a software bundle of related state and behavior. The main advantage of java is you can compare objects in Java with real world objects. So it is very easy to work with objects in Java

 

What Is a Class?

A class is a blueprint or prototype from which objects are created.

 

 

How to define a class?

You can define a class using ‘class’ keyword.

 

Syntax

class ClassName{
    
}

 

As per the convention, class name starts with a capital letter and every first character in subsequent word also a capital letter.

 

Example 1

class Person{
    
}

 

Example 2

class EmployeeInfo{
    
}

 

What are properties and methods?

Variables defined in a class are called properties and functions defined in a class are called methods.

 

How to define properties in a class?

Using ‘var’ keyword, you can define properties in a class. For example, following snippet defines four variables $id, $first_name, $last_name and $age.

 

class Employee{

    var $id;
    var $first_name;
    var $last_name;
    var $age;
    ......
    ......

}

 

What is constructor?

Constructor is used to instantiate an object at the time of creation. You can define a construction using ‘function’ keyword and __construct function.

 

class Employee{
    var $id;
    var $first_name;
    var $last_name;
    var $age;

    function __construct($id, $first_name, $last_name, $age){
        $this->id = $id;
        $this->first_name = $first_name;
        $this->last_name = $last_name;
        $this->age = $age;
    }
    ......
    ......
}

$this is used to refer current instance or object properties.

 

Public and private methods

Within a class, you can define both public and private method. Public methods can be called by an object, whereas private methods are accessible within the class.

 

You can define a public method using ‘public’ keyword.

public function set_age($new_age){
    $this->age = $new_age;
}


You can define a private method using ‘private’ keyword.

private function full_name(){
    return $this->get_first_name() . ',' . $this->get_last_name();
}


How to define an object?

An object is created using new keyword followed by class name and constructor arguments.

 

Example

$emp1 = new Employee(1, 'Krishna', 'Gurram', 31);

 

How to call the methods of an object?

Syntax

$object_name -> method_name(arguments);

 

Example

$emp1->to_string();

 

Find the below working example.

 

 

class_demo_1.php

#!/usr/bin/php

<?php

class Employee{
    var $id;
    var $first_name;
    var $last_name;
    var $age;

    function __construct($id, $first_name, $last_name, $age){
        $this->id = $id;
        $this->first_name = $first_name;
        $this->last_name = $last_name;
        $this->age = $age;
    }

    // Gettter methods
    public function get_id(){
        return $this->id;
    }

    public function get_first_name(){
        return $this->first_name;
    }

    public function get_last_name(){
        return $this->last_name;
    }
    
    public function get_age(){
        return $this->age;
    }

    // Setter methods
    public function set_id($new_id){
        $this->id = $new_id;
    }

    public function set_first_name($new_first_name){
        $this->first_name = $new_first_name;
    }

    public function set_last_name($new_last_name){
        $this->last_name = $new_last_name;
    }

    public function set_age($new_age){
        $this->age = $new_age;
    }

    public function to_string(){
        return $this->get_id() . ', ' . $this->full_name() . ', ' . $this->get_age();
    }

    // private methods
    private function full_name(){
        return $this->get_first_name() . ',' . $this->get_last_name();
    }
}

$emp1 = new Employee(1, 'Krishna', 'Gurram', 31);
$emp2 = new Employee(2, 'Chamu', 'Gurram', 30);

echo"id, name, age\n";
echo $emp1->to_string();
echo "\n";
echo $emp2->to_string();

?>


Output

$./class_demo_1.php 

id, name, age
1, Krishna,Gurram, 31
2, Chamu,Gurram, 30






 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home