How do I find entity by their ID in JPA?

In this example you will learn how to find an entity object by its ID using JPA. To find entity by their ID, we use the EntityManager.find() method and pass the entity class and the entity ID as the parameters.

In the code snippet below the EntityManager required by the ArtistDaoImpl will be passed from the main program when the DAO is instantiated. The process of finding the Artist entity is defined in the findById() method in the DAO class. You must pass the ID of the entity to this method.

The findById() method call the EntityManager.find() method to find the entity. If no entity was found, where the artist == null a javax.persistence.EntityNotFoundException will be thrown.

package org.kodejava.jpa.dao.impl;

import org.kodejava.jpa.dao.ArtistDao;
import org.kodejava.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import java.util.List;

public class ArtistDaoImpl implements ArtistDao {
    private final EntityManager manager;

    public ArtistDaoImpl(EntityManager manager) {
        this.manager = manager;
    }

    /**
     * Find Artist based on the entity id.
     *
     * @param artistId the artist id.
     * @return Artist.
     * @throws EntityNotFoundException when no artist is found.
     */
    public Artist findById(Long artistId) {
        Artist artist = manager.find(Artist.class, artistId);
        if (artist == null) {
            throw new EntityNotFoundException("Can't find Artist for ID "
                    + artistId);
        }
        return artist;
    }

    @Override
    public void save(Artist artist) {
        manager.getTransaction().begin();
        manager.persist(artist);
        manager.getTransaction().commit();
    }

    @Override
    @SuppressWarnings(value = "unchecked")
    public List<Artist> getArtists() {
        Query query = manager.createQuery("select a from Artist a", Artist.class);
        return query.getResultList();
    }
}

To run the DAO class we create a main program in the code snippet below. The steps are creating the EntityManagerFactory configured in your persistence.xml file. Create the EntityManager using the factory object. Create the DAO and pass the EntityManager to it. And finally call the findById() method of the DAO class.

package org.kodejava.jpa;

import org.kodejava.jpa.dao.ArtistDao;
import org.kodejava.jpa.dao.impl.ArtistDaoImpl;
import org.kodejava.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;

public class FindEntityByIdDemo {
    public static final String PERSISTENCE_UNIT_NAME = "music";

    public static void main(String[] args) {
        EntityManagerFactory factory =
                Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager em = factory.createEntityManager();

        ArtistDao dao = new ArtistDaoImpl(em);

        // Find an artist with ID = 1 from the database. The entity is
        // exists in the database.
        Artist artist = dao.findById(1L);
        System.out.println("Artist = " + artist);

        try {
            // Find an entity that is not exists in the database will
            // throw an exception.
            artist = dao.findById(100L);
            System.out.println("Artist = " + artist);
        } catch (EntityNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>javax.persistence-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I find and replace string?

The code below demonstrates the use Matcher.appendReplacement() and Matcher.appendTail() methods to create a program to find and replace a sub string within a string.

Another solution that can be used to search and replace a string can be found on the following example: How do I create a string search and replace using regex?.

package org.kodejava.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AppendReplacementExample {
    public static void main(String[] args) {
        // Create a Pattern instance
        Pattern pattern = Pattern.compile("[Pp]en");

        // Create matcher object
        String input = "Please use your Pen to answer the question, " +
                "black pen is preferred.";
        Matcher matcher = pattern.matcher(input);
        StringBuilder builder = new StringBuilder();

        // Find and replace the text that match the pattern
        while (matcher.find()) {
            matcher.appendReplacement(builder, "pencil");
        }

        // This method reads characters from the input sequence, starting
        // at the beginning position, and appends them to the given string
        // builder. It is intended to be invoked after one or more
        // invocations of the appendReplacement method in order to copy
        // the remainder of the input sequence.
        matcher.appendTail(builder);

        System.out.println("Input : " + input);
        System.out.println("Output: " + builder);
    }
}

Here is the result of the above code:

Input : Please use your Pen to answer the question, black pen is preferred.
Output: Please use your pencil to answer the question, black pencil is preferred.

How do I create a string search and replace using regex?

In this example you’ll see how we can create a small search and replace program using the regular expression classes in Java. The code below will replace all the brown words to red.

package org.kodejava.regex;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class StringReplace {
    public static void main(String[] args) {
        String source = "The quick brown fox jumps over the brown lazy dog.";
        String find = "brown";
        String replace = "red";

        // Compiles the given regular expression into a pattern.
        Pattern pattern = Pattern.compile(find);

        // Creates a matcher that will match the given input against the
        // pattern.
        Matcher matcher = pattern.matcher(source);

        // Replaces every subsequence of the input sequence that matches
        // the pattern with the given replacement string.
        String output = matcher.replaceAll(replace);

        System.out.println("Source = " + source);
        System.out.println("Output = " + output);
    }
}

The result of the code snippet is:

Source = The quick brown fox jumps over the brown lazy dog.
Output = The quick red fox jumps over the red lazy dog.