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.
1 2 3 4 5 6 7 8 9 10 11 12 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
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."); } } } |
1 2 3 4 5 6 7 |
public void putSomeEntity(String name, int age) { SomeEntity someEntity = EntityUtil.defaultEntity(someEntityRepository.findByName(name), SomeEntity.class); someEntity.setAge(age); someEntityRepository.save(someEntity); } |
Also published on Medium.