POJO コード例
import java.util.Optional;
/**
* org.springframework.data.repository.CrudRepository と同等のインタフェース
* Springに依存しないPOJOで定義する
* @author murayama
* @param <T> エンティティ型
* @param <ID> JPA識別子型
*/
public interface ICrudRepository<T, ID> {
public <S extends T> S save(S entity);
public <S extends T> Iterable<S> saveAll(Iterable<S> entities);
public Optional<T> findById(ID id);
public boolean existsById(ID id);
public Iterable<T> findAll();
public Iterable<T> findAllById(Iterable<ID> ids);
public long count();
public void deleteById(ID id);
public void delete(T entity);
public void deleteAllById(Iterable<? extends ID> ids);
public void deleteAll(Iterable<? extends T> entities);
public void deleteAll();
}
import java.lang.reflect.Method;
import java.util.Collection;
import domain.BaseEntity;
public abstract class BaseRepository {
private static final Long MIN_SEQ = 1L;
private static Long seq4Id = MIN_SEQ;
private static synchronized Long newId() {
return seq4Id++;
}
/**
* 引数のエンティティおよび参照先エンティティのIdが未設定の場合、Idを設定する
* @param entity
*/
protected void fillIds(BaseEntity entity) {
if (entity == null) {
throw new RuntimeException("BaseRepository#fillIds entity is null例外");
}
if (checkIfNew(entity)) {
entity.setId(newId()); // Id設定
}
for (Method m : entity.getClass().getDeclaredMethods()) {
Object returnVal = null;
if (checkIfGetter(m)) {
returnVal = getReturnVal(entity, m);
if (returnVal instanceof BaseEntity) {
BaseEntity returnedEntity = (BaseEntity) returnVal;
if (checkIfNew(returnedEntity)) {
returnedEntity.setId(newId()); // Id設定
}
} else if (returnVal instanceof Collection) {
for (Object child : (Collection<Object>) returnVal) {
if (child instanceof BaseEntity) { //CollectionのCollectionは無視
this.fillIds((BaseEntity) child);
}
}
}
}
}
}
/** インスタンスメソッドを起動して戻り値を応答する */
private static Object getReturnVal(BaseEntity entity, Method m) {
try {
return m.invoke(entity);
} catch (Exception ex) {
throw new RuntimeException("BaseRepository#getReturnVal Method#invoke例外: " + m.getName());
}
}
/** getterメソッドか否か */
private static boolean checkIfGetter(Method method) {
return method != null && (!method.getReturnType().getName().equals("void"))
&& method.getName().startsWith("get") && method.getParameterCount() < 1;
}
/** Id未決のエンティティか否か */
private static boolean checkIfNew(BaseEntity entity) {
return entity != null && entity.getId() < MIN_SEQ;
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import domain.Employee;
/**
* 社員リポジトリ(シングルトン)
* @author murayama
*
*/
public class EmployeeRepository extends BaseRepository implements ICrudRepository<Employee, Long>{
/** シングルトンインスタンス */
private static EmployeeRepository instance = null;
/** 社員リスト */
private List<Employee> employeeList;
/** シングルトン応答 */
public static synchronized EmployeeRepository getInstance() {
if (instance == null) {
instance = new EmployeeRepository();
}
return instance;
}
/** コンストラクタ */
private EmployeeRepository() {
employeeList = new ArrayList<>();
}
//ICrudRepositoryインタフェースの実装
@Override
@SuppressWarnings("unchecked")
public Employee save(Employee entity) {
if (entity != null) {
fillIds(entity);
this.employeeList.add(entity);
}
return entity;
}
@Override
public <S extends Employee> Iterable<S> saveAll(Iterable<S> entities) {
throw new RuntimeException("未実装:saveAll");
}
@Override
public Optional<Employee> findById(Long id) {
List<Employee> list = this.employeeList.stream().filter(e -> e.getId() == id).collect(Collectors.toList());
if (list.size() == 1) {
return Optional.of(list.get(0));
}
return Optional.empty();
}
@Override
public boolean existsById(Long id) {
throw new RuntimeException("未実装:existsById");
}
@Override
public Iterable<Employee> findAll() {
throw new RuntimeException("未実装:findAll");
}
@Override
public Iterable<Employee> findAllById(Iterable<Long> ids) {
throw new RuntimeException("未実装:findAllById");
}
@Override
public long count() {
throw new RuntimeException("未実装:count");
}
@Override
public void deleteById(Long id) {
throw new RuntimeException("未実装:deleteById");
}
@Override
public void delete(Employee entity) {
throw new RuntimeException("未実装:delete");
}
@Override
public void deleteAllById(Iterable<? extends Long> ids) {
throw new RuntimeException("未実装:deleteAllById");
}
@Override
public void deleteAll(Iterable<? extends Employee> entities) {
throw new RuntimeException("未実装:deleteAll");
}
@Override
public void deleteAll() {
throw new RuntimeException("未実装:deleteAll");
}
//追加メソッドを実装
/** 名前で検索する */
public List<Employee> findByName(String name) {
List<Employee> resultList = new ArrayList<>();
this.employeeList.stream()
.filter(e -> name.equals(e.getName()))
.forEach(e -> resultList.add(e));
return resultList;
}
}
import java.io.Serializable;
/**
* ドメインオブジェクトの基底クラス
* @author murayama
*
*/
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/** JPA識別子 */
protected Long id;
/** コンストラクタ */
public BaseEntity() {
this.id = 0L;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
}
import java.util.ArrayList;
import java.util.List;
/**
* 社員
* @author murayama
*
*/
public class Employee extends BaseEntity{
private static final long serialVersionUID = 1L;
private String name = "";
private List<Device> deviceList;
public Employee() {
this.name = "";
this.deviceList = new ArrayList<>();
}
public void addDevice(Device d) {
if (d != null && ! this.deviceList.contains(d)) {
this.deviceList.add(d);
d.setEmployee(this);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Device> getDeviceList() {
return deviceList;
}
public void setDeviceList(List<Device> deviceList) {
this.deviceList = deviceList;
}
}
public class Device extends BaseEntity {
private static final long serialVersionUID = 1L;
private Employee employee;
public Device() {
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
/**
* Javaアプリケーション起動クラス
*/
public class Starter {
public static void main(String[] args) {
(new Starter()).doTest();
}
private EmployeeRepository employeeRepository = EmployeeRepository.getInstance();
private void doTest() {
Employee employee = new Employee();
employee.setId();
employee.setName("ネクスト");
employeeRepository.save(employee);
return; //ブレークして employee の内容を確認する
}
}