Posts

Showing posts from September, 2020

Difference between Comparator and Comparable

Java has two interfaces that you can use for sorting custom objects. These are the Comparator and Comparable interface. In this article, I will be explaining the differences between the two. Basic difference between Comparator and Comparable The main difference between the Comparator and Comparable interface is that you can use Comparator  to compare two independent objects. The Comparable on the other hand is used to compare the current object with another object. Consider the following Person class: public class Person { private String name; private int age; public Person(String name, int age) { super(); this.name = name; this.age = age; }} Suppose you want to sort Person objects on the basis of the age fields. Let us understand how you can achieve this using both Comparator and Comparable. Sorting Using Comparator In order to sort using Comparator, you will first need to create a class that implements the Comparator interface.  The following code demonstrates this

Introduction to JPA - The Why, What and How of JPA

Image
In this article, I will be giving you an Introduction to JPA.. I will be explaining what was the need for JPA, what JPA is and how it works. Need for JPA In the early days of programming, JDBC was widely used to access a database table from Java code.  It allows querying/updating database tables from Java code.  The downside of JDBC is that is is very verbose. You need to directly write SQL statements in the code. Secondly, it is not object-oriented, so it becomes difficult to map database tables to Java classes and vice versa. Also, since it uses SQL directly in the code, developers may tend to use database specific SQL and thus make the code database dependent. To overcome all these limitations, ORM frameworks were developed.  ORM stands for Object Relational Mapping.  An ORM framework helps to map a database table to a Java class and vice versa and thus does away with all the boilerplate code associated with JDBC. Some popular ORM frameworks are Hibernate and TopLink. However, ove