Sunday, 7 November 2021

Spring Data: ArangoDB: Sort by multiple keys

You can sort the documents in a collection on multiple properties.

 

For example, below snippet Sort the documents in the ascending order of employee age and descending order of their firstName.

Iterable<Employee> empIterable = employeeRepo.findAll(Sort.by(Arrays.asList(Sort.Order.asc("age"), Sort.Order.desc("firstName"))));

Follow below step-by-step procedure to build complete working application.

 

Step 1: Create new maven project ‘sort-by-doc-properties-demo’.

 

Step 2: Update pom.xml with below 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>sort-by-doc-properties-demo</artifactId>
  <version>1</version>

  <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
  </parent>


  <dependencies>
    <dependency>
      <groupId>com.arangodb</groupId>
      <artifactId>arangodb-spring-boot-starter</artifactId>
      <version>2.3.3.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>


Step 3: Define Employee entity class.

 

Employee.java

package com.sample.app.entity;

import com.arangodb.springframework.annotation.ArangoId;
import com.arangodb.springframework.annotation.Document;
import org.springframework.data.annotation.Id;

@Document("employees")
public class Employee {

  @Id // db document field: _key
  private String key;

  @ArangoId // db document field: _id
  private String arangoId;

  private Integer id;
  private String firstName;
  private String lastName;
  private Integer age;

  public Employee(Integer id, String firstName, String lastName, Integer age) {
    super();
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public String getArangoId() {
    return arangoId;
  }

  public void setArangoId(String arangoId) {
    this.arangoId = arangoId;
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer 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 Integer getAge() {
    return age;
  }

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

  @Override
  public String toString() {
    return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]";
  }

}


Step 4: Define EmployeeRepository interface.

 

EmployeeRepository.java

package com.sample.app.repository;

import com.arangodb.springframework.repository.ArangoRepository;
import com.sample.app.entity.Employee;

public interface EmployeeRepository extends ArangoRepository<Employee, String> {

}


Step 5: Define Arango db configuration class.

 

ArangoConfig.java

package com.sample.app.config;

import com.arangodb.ArangoDB;
import com.arangodb.springframework.annotation.EnableArangoRepositories;
import com.arangodb.springframework.config.ArangoConfiguration;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableArangoRepositories(basePackages = { "com.sample.app" })
public class ArangoConfig implements ArangoConfiguration {

  @Override
  public ArangoDB.Builder arango() {
    return new ArangoDB.Builder().host("localhost", 8529).user("root").password("tiger");
  }

  @Override
  public String database() {
    return "abc_org";
  }
}

 

Step 6: Define main application class.

 

App.java

 

package com.sample.app;

import java.util.Arrays;
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.domain.Sort;

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

  @Bean
  public CommandLineRunner demo(EmployeeRepository employeeRepo) {
    return (args) -> {
      List<Employee> emps = Arrays.asList(new Employee(1, "Ram", "Gurram", 31),
          new Employee(2, "Sundar", "Deavanagari", 32), new Employee(3, "Srinuvasa rao", "Guma", 43),
          new Employee(4, "Madhavi Latha", "Gumma", 41), new Employee(5, "Gopi", "Battu", 33),
          new Employee(6, "Sailu", "PTR", 33), new Employee(7, "Venkat", "PTR", 32));

      employeeRepo.saveAll(emps);

      Iterable<Employee> empIterable = employeeRepo
          .findAll(Sort.by(Arrays.asList(Sort.Order.asc("age"), Sort.Order.desc("firstName"))));

      for (Employee emp : empIterable) {
        System.out.println(emp);
      }
    };
  }
}

 

Total project structure looks like below.

 


 

 

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

Employee [id=1, firstName=Ram, lastName=Gurram, age=31]
Employee [id=7, firstName=Venkat, lastName=PTR, age=32]
Employee [id=2, firstName=Sundar, lastName=Deavanagari, age=32]
Employee [id=6, firstName=Sailu, lastName=PTR, age=33]
Employee [id=5, firstName=Gopi, lastName=Battu, age=33]
Employee [id=4, firstName=Madhavi Latha, lastName=Gumma, age=41]
Employee [id=3, firstName=Srinuvasa rao, lastName=Guma, age=43]


You can download complete working application below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/sort-by-doc-properties-demo

 

 

Previous                                                    Next                                                    Home

Java: How to access this from Anonymous class?

Using ‘ClassName.this’, you can access the properties/methods associated with an object from anonymous class.

 

AccessThisFromAnonymousClass.java

package com.sample.app.classes;

public class AccessThisFromAnonymousClass {

	private final double PI = 3.14;

	private interface Circle {
		public double area(double radius);
	}

	public static void main(String args[]) {
		Circle c1 = new Circle() {

			@Override
			public double area(double radius) {
				return AccessThisFromAnonymousClass.this.PI * radius * radius;
			}

		};

		double area = c1.area(5);

		System.out.println(area);
	}

}

Output

78.5


You may like

Interview Questions

Java: Get the index of first occurrence of a substring

Java: Get the index of last occurrence of a substring

Java: Get all the indexes of occurrence of a substring

Java: How to replace a value in ArrayList or LinkedList

Why do we declare logger with static and final?

Java: Convert byte array to an integer

In this post, I am going to explain how to convert byte array to an integer. While converting the byte array to integer, we should consider the byte order also.

 

There are two standard byte array order formats.

a.   BIG_ENDIAN: In this order, the bytes of a multibyte value are ordered from most significant to least significant.

b.   LITTLE_ENDIAN: In this order, the bytes of a multibyte value are ordered from least significant to most significant.

 

For example, below snippet convert the byte array in BIG_ENDIAN format to an integer.

 

int intInBigEndian = ByteBuffer.wrap(byteArr1).order(ByteOrder.BIG_ENDIAN).getInt();

 

ByteArrayToInteger.java

package com.sample.app.numbers;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class ByteArrayToInteger {

	public static void main(String args[]) {
		byte[] byteArr1 = { 0, -68, 97, 78 };

		int intVal = ByteBuffer.wrap(byteArr1).order(ByteOrder.BIG_ENDIAN).getInt();

		System.out.println("intVal -> " + intVal);
	}

}

 

Output

intVal -> 12345678

 

 

 

You may like

Java: Get native byte order of the underlying platform

ByteOrder.nativeOrder() method return the native byte order of the hardware upon which this Java virtual machine is running. This is different from jvm byte order.

 

As per the below stackoverflow post, JVM follows big-endian format irrespective of the underlying platform byte order.

https://stackoverflow.com/questions/362384/does-java-read-integers-in-little-endian-or-big-endian

 

NativeByteOrder.java

package com.sample.app.numbers;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class NativeByteOrder {

	public static void main(String args[]) {
		System.out.println("Native system byte order " + ByteOrder.nativeOrder());

		ByteBuffer bb = ByteBuffer.allocate(2);
		System.out.println("JVM Default Byte Order: " + bb.order());
	}

}

 

Output

Native system byte order LITTLE_ENDIAN
JVM Default Byte Order: BIG_ENDIAN

  

You may like

Java: Convert integer to byte array

In this post, I am going to explain multiple approaches how to convert an integer to the byte array. Be cautious about the byte orders while converting the integer to byte array.

 

There are two standard byte array order formats.

a.   BIG_ENDIAN: In this order, the bytes of a multibyte value are ordered from most significant to least significant.

b.   LITTLE_ENDIAN: In this order, the bytes of a multibyte value are ordered from least significant to most significant.

 

Approach 1: Using custom business logic.

public static byte[] toByteArray(int i) {
	byte[] result = new byte[4];

	result[0] = (byte) (i >> 24);
	result[1] = (byte) (i >> 16);
	result[2] = (byte) (i >> 8);
	result[3] = (byte) (i);

	return result;
}

 

IntToByteArray.java

package com.sample.app.numbers;

public class IntToByteArray {

	public static byte[] toByteArray(int i) {
		byte[] result = new byte[4];

		result[0] = (byte) (i >> 24);
		result[1] = (byte) (i >> 16);
		result[2] = (byte) (i >> 8);
		result[3] = (byte) (i);

		return result;
	}

	public static void printByteArray(byte[] byteArr) {
		for (byte b : byteArr) {
			System.out.print(b + "\t");
		}
	}

	public static void main(String args[]) {
		byte[] byteArr = toByteArray(12345678);
		printByteArray(byteArr);
	}
}

 

Output

0	-68	97	78	

 

Approach 2: Using ByteBuffer.

public static byte[] toByteArray(int i) {
	ByteBuffer b = ByteBuffer.allocate(4);
	b.order(ByteOrder.BIG_ENDIAN);
	b.putInt(i);

	return b.array();
}

 

IntToByteArray1.java

package com.sample.app.numbers;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class IntToByteArray1 {

	public static byte[] toByteArray(int i) {
		ByteBuffer b = ByteBuffer.allocate(4);
		b.order(ByteOrder.BIG_ENDIAN);
		b.putInt(i);

		return b.array();
	}

	public static void printByteArray(byte[] byteArr) {
		for (byte b : byteArr) {
			System.out.print(b + "\t");
		}
	}

	public static void main(String args[]) {
		byte[] byteArr = toByteArray(12345678);
		printByteArray(byteArr);
	}
}

 

Output

0	-68	97	78	

 

One advantage of using ByteBuffer is, it gives flexibility to choose the byte order(BIG_ENDIAN, LITTLE_ENDIAN).

 

Approach 3: Using BigInteger#toByteArray method

BigInteger#toByteArray method return byte array containing the two's-complement representation of this BigInteger.  The byte array will be in big-endian byte-order.

 

IntToByteArray2.java

 

 

package com.sample.app.numbers;

import java.math.BigInteger;

public class IntToByteArray2 {

	public static byte[] toByteArray(int i) {
		BigInteger bigInt = BigInteger.valueOf(i);
		return bigInt.toByteArray();
	}

	public static void printByteArray(byte[] byteArr) {
		for (byte b : byteArr) {
			System.out.print(b + "\t");
		}
	}

	public static void main(String args[]) {
		byte[] byteArr = toByteArray(12345678);
		printByteArray(byteArr);
	}
}


Output

0	-68	97	78	


Approach 4: Using DataOutputStream.

public static byte[] toByteArray(int i) throws IOException {
	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
	dataOutputStream.writeInt(i);
	dataOutputStream.flush();
	return byteArrayOutputStream.toByteArray();
}


IntToByteArray3.java

package com.sample.app.numbers;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class IntToByteArray3 {

	public static byte[] toByteArray(int i) throws IOException {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
		dataOutputStream.writeInt(i);
		dataOutputStream.flush();
		return byteArrayOutputStream.toByteArray();
	}

	public static void printByteArray(byte[] byteArr) {
		for (byte b : byteArr) {
			System.out.print(b + "\t");
		}
	}

	public static void main(String args[]) throws IOException {
		byte[] byteArr = toByteArray(12345678);
		printByteArray(byteArr);
	}
}


Output

0	-68	97	78	

 

You may like