Showing posts with label count. Show all posts
Showing posts with label count. Show all posts

Tuesday, 20 April 2021

Spring jpa: count entities using query method

You can use count queries to calculate overall number of entities matches to given query.

 

Example 1: Count all the employees with matching firstName.

long countByFirstName(String firstName);

 

Example 2: Count all the employee with matching lastName.

long countByLastName(String lastName);

 

Example 3: Count all the employees with matching age.

long countByAge(int age);

 

Example 4: Count all the employees with given age or firstName.

long countByAgeOrFirstName(int age, String firstName);

 

Find the below working application.

 

Step 1: Create new maven project ‘count-query-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>count-query-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 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=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.

 

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 org.springframework.data.jpa.repository.JpaRepository;

import com.sample.app.entity.Employee;

public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
	long countByFirstName(String firstName);

	long countByLastName(String lastName);

	long countByAge(int age);

	long countByAgeOrFirstName(int age, String firstName);

}

 

Step 6: Define main application class.

 

App.java

package com.sample.app;

import java.util.List;

import javax.transaction.Transactional;

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
	@Transactional
	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.findAll();
			printEmployees(emps, "All the employees information");

			long empsByFirstNameCount = employeeRepository.countByFirstName("Ram");
			System.out.println("Total employee with firstName 'Ram' : " + empsByFirstNameCount);

			long empsByLastNameCount = employeeRepository.countByLastName("Sami");
			System.out.println("Total employee with lastName 'Sami' : " + empsByLastNameCount);

			long empsWithAge32Count = employeeRepository.countByAge(32);
			System.out.println("Total employee with age 32 : " + empsWithAge32Count);

			long empsWithAge32OrFirstNameIsRam = employeeRepository.countByAgeOrFirstName(32, "Ram");
			System.out.println("Total employee with age 32 or firstName is 'Ram': " + empsWithAge32OrFirstNameIsRam);

		};
	}

} 

 

Total project structure looks like below.


 

Run App.java, you will see below messages in console.

 

All the employees information
Employee [id=1, firstName=Ram, lastName=Gurram, age=32, salary=100000.23]
Employee [id=2, firstName=Ram, lastName=Chelli, age=43, salary=60000.0]
Employee [id=3, firstName=Gopi, lastName=Battu, age=45, salary=1000000.0]
Employee [id=4, firstName=Ram, lastName=Srikanth, age=39, salary=60000.0]
Employee [id=5, firstName=Surendra, lastName=Sami, age=32, salary=100000.23]

Total employee with firstName 'Ram' : 3
Total employee with lastName 'Sami' : 1
Total employee with age 32 : 2
Total employee with age 32 or firstName is 'Ram': 4


You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/jpa/count-query-demo



 

 

 

 

  

Previous                                                    Next                                                    Home

Sunday, 4 April 2021

Php: array: count: count number of elements in the array

count ( Countable|array $value , int $mode = COUNT_NORMAL ) : int

 

Description

Counts all elements in an array, or something in an object.

 

Parameters:

mode: If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array

 

array_count_elements.php

#!/usr/bin/php

<?php

    $arr1 = array(2, 3, 5, 7);
    $arr2 = [[1, 2, 3, 4], [5, 6, 7, 8]];

    $number_of_elements = count($arr1);
    echo "number of elements in the array arr1 : $number_of_elements\n";

    $number_of_elements = count($arr2, 1);
    echo "number of elements in the array arr2 : $number_of_elements\n";
?>

 

Output

$./array_count_elements.php 

number of elements in the array arr1 : 4
number of elements in the array arr2 : 10

 

 

 

 

Previous                                                    Next                                                    Home

Tuesday, 31 March 2020

TableSaw: count: Count number of elements that satisfy given predicate

default int count(Predicate<? super T> test)
‘count’ function returns number of elements that satisfy given predicate.

Example : Count number of elements that are > 20
Predicate<Integer> predicate = new Predicate<Integer> () {

         @Override
         public boolean test(Integer t) {
                  return t > 20;
         }
        
};

int eleGreater20 = numbersColumn.count(predicate);

App.java
package com.sample.app;

import java.util.function.Predicate;

import tech.tablesaw.api.IntColumn;

public class App {

 public static void main(String args[]) {
  int[] numbers = { 23, 45, 6, 32, 1, 43 };
  
  IntColumn numbersColumn = IntColumn.create("My Numbers", numbers);
  
  Predicate<Integer> predicate = new Predicate<Integer> () {

   @Override
   public boolean test(Integer t) {
    return t > 20;
   }
   
  };
  
  int eleGreater20 = numbersColumn.count(predicate);
  

  System.out.println("Total number of elements > 20 : " + eleGreater20);
 }
}

Output
Total number of elements > 20 : 4




Previous                                                    Next                                                    Home

Count number of lines in a file

Approach 1: Checking for the character \n.
public static long countLines_1(String filePath) throws IOException {
 if (filePath == null || filePath.isEmpty()) {
  throw new IllegalArgumentException("File name must not null or empty");
 }

 try (InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath))) {

  File file = new File(filePath);

  if (file.length() == 0) {
   return 0;
  }

  byte[] buffer = new byte[1024];
  long count = 0;
  int currentChar = 0;

  while ((currentChar = inputStream.read(buffer)) != -1) {

   for (int i = 0; i < currentChar; ++i) {
    if (buffer[i] == '\n') {
     count++;
    }
   }
  }
  return count;
 }
}

Step 2: Using LineReader.
public long countLines_2(String filePath) throws IOException {
 if (filePath == null || filePath.isEmpty()) {
  throw new IllegalArgumentException("File name must not null or empty");
 }

 try (LineNumberReader reader = new LineNumberReader(new FileReader(filePath))) {
  String lineRead = "";
  while ((lineRead = reader.readLine()) != null) {
  }

  return reader.getLineNumber();
 }

}


App.java

package com.sample.app;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;

public class App {

 public static long countLines_1(String filePath) throws IOException {
  if (filePath == null || filePath.isEmpty()) {
   throw new IllegalArgumentException("File name must not null or empty");
  }

  try (InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath))) {

   File file = new File(filePath);

   if (file.length() == 0) {
    return 0;
   }

   byte[] buffer = new byte[1024];
   long count = 0;
   int currentChar = 0;

   while ((currentChar = inputStream.read(buffer)) != -1) {

    for (int i = 0; i < currentChar; ++i) {
     if (buffer[i] == '\n') {
      count++;
     }
    }
   }
   return count;
  }
 }

 public long countLines_2(String filePath) throws IOException {
  if (filePath == null || filePath.isEmpty()) {
   throw new IllegalArgumentException("File name must not null or empty");
  }

  try (LineNumberReader reader = new LineNumberReader(new FileReader(filePath))) {
   String lineRead = "";
   while ((lineRead = reader.readLine()) != null) {
   }

   return reader.getLineNumber();
  }

 }

 public static void main(String args[]) throws IOException {
  String filePath = "/Users/Shared/data.txt";

  long noOfLines = countLines_1(filePath);

  System.out.println("Number Of Lines : " + noOfLines);
 }

}


You may like

Monday, 3 February 2020

Cassandra: Count number of rows in a table


Below statement return number of rows in a table.

SELECT COUNT(*) FROM {TABLE_NAME};

cqlsh> CREATE KEYSPACE cassandratutorial WITH REPLICATION = 
   ... { 
   ...   'class' : 'SimpleStrategy', 
   ...   'replication_factor' : 1 
   ... };
cqlsh> 
cqlsh> CREATE TABLE IF NOT EXISTS cassandratutorial.employee (
   ...   id INT PRIMARY KEY, 
   ...   firstName VARCHAR,
   ...   lastName VARCHAR,
   ...   age int
   ... );
cqlsh> 
cqlsh> 
cqlsh> INSERT INTO cassandratutorial.employee JSON '{"id" : 1, "firstName" : "Krishna", "lastName" : "Gurram", "age" : 30}';
cqlsh> INSERT INTO cassandratutorial.employee JSON '{"id" : 2, "firstName" : "Ram", "lastName" : "Gurram", "age" : 31}' ;
cqlsh> INSERT INTO cassandratutorial.employee JSON '{"id" : 3, "firstName" : "Vijay", "lastName" : "Ponnam", "age" : 45}';
cqlsh> INSERT INTO cassandratutorial.employee JSON '{"id" : 4, "firstName" : "Chitra", "lastName" : "Rajan", "age" : 45}';
cqlsh> 
cqlsh> SELECT COUNT(*) FROM cassandratutorial.employee;

 count
-------
     4

(1 rows)

Warnings :
Aggregation query used without partition key




Previous                                                    Next                                                    Home