EntityUtil.java code snippet
2 min readJun 1, 2018
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();
someEntity.setName(name);
}
someEntity.setAge(age);
someEntityRepository.save(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);
someEntity.setAge(age);
someEntityRepository.save(someEntity);
}
Originally published at ThinkCUBES.