EntityUtil.java code snippet

Hyeonho Martin Kang
Jun 1, 2018 · 2 min read

I usually do ‘select’ query before ‘update’ or ‘insert’ query using Jpa, Java.

For example, I must create new entity if the entity is null by ‘select’ query, or I do just setAge(); if the entity exists.

So I code as below by most commonly.

public void putSomeEntity(String name, int age) {
SomeEntity someEntity = someEntityRepository.findByName(name);

if (someEntity == null) {
someEntity = new SomeEntity();



I don’t want to do it, checking null, always. It is very pesky pattern.

So I create a utility class as below.

package kr.co.freeism.util;

import com.google.common.base.Preconditions;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;

* @author freeism
* @since 2018. 6. 2.
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class EntityUtil {
* return new Entity by default constructor, if null
* return bypassing the Entity, given method parameter
* @param obj the target for checking null. need to declare @Entity annotation
* @param clazz default entity type for returning, if the object is null
* @return obj != null ? obj : new obj()
* @throws NullPointerException If clazz is null.
* @throws IllegalArgumentException If @Entity annotaion is missing.
* @throws IllegalArgumentException If clazz.newInstance() throws Exception.
public static <T> T defaultEntity(T obj, Class<T> clazz) {
Preconditions.checkNotNull(clazz, "clazz must be defined.");
Preconditions.checkArgument(clazz.isAnnotationPresent(Entity.class), "clazz must be Entity annotated class.");

try {
return obj == null ? clazz.newInstance() : obj;
} catch (IllegalAccessException | InstantiationException e) {
throw new IllegalArgumentException("clazz must have default constructor.");
public void putSomeEntity(String name, int age) {
SomeEntity someEntity = EntityUtil.defaultEntity(someEntityRepository.findByName(name), SomeEntity.class);



Originally published at ThinkCUBES.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade