将保存实现转换为通用方式

时间:2017-07-18 18:30:57

标签: java generics

我尝试使用通用方法来保存实体,有一个转换阶段要做。

我尝试将我的save方法放在一个抽象类

public class SportsServiceImpl extends BaseService implements SportsService {

        public void save(SportsDto SportsDto) {

            Sports Sports = null;

            if (SportsDto == null) {
                //throw error
            }

            if (SportsDto.getId() != null) {
                Optional<Sports> SportsOpt = SportsRepository.findById(SportsDto.getId());

                if (SportsOpt.isPresent()) {
                    Sports = SportsOpt.get();
                }
            }

            if (Sports == null) {
                Sports = new Sports();
            }

            convertToBeans(SportsDto, Sports);

            SportsRepository.save(Sports);

     }

}

试着放在这里

public abstract class BaseService<T> {

    private JpaRepository<T, Integer> repository;

        public <T extends BaseEntity, R  extends BaseDto> void save(R r){
        T t = null;

        if (r == null) {
            //throw error
        }

        if (r.getId() != null) {
            Optional<T> tOpt = null;
            try {
                tOpt = (Optional<T>) repository.findById(t.getClass().getField("id").getInt(t));
            } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
                Logger.getLogger(BaseService.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (tOpt!=null && tOpt.isPresent()) {
                t = tOpt.get();
            }
        }

        if (t == null) {
            t = new T();           //seem not able to do this
        }

        convertToBeans(r, t);   //java don't like that

        repository.save(t);
    }

convertToBeans在扩展BaseService的类中

尝试传递save function convertToBeans

的参数

但得到相同的结果

有没有办法以通用方式完成

1 个答案:

答案 0 :(得分:1)

你可以使你的转换方法抽象化:

public abstract class BaseService<T, R> {

private JpaRepository<T, Integer> repository;

    public <T extends BaseEntity, R  extends BaseDto> void save(R r){
    T t = null;

    if (r == null) {
        //throw error
    }

    if (r.getId() != null) {
        Optional<T> tOpt = null;
        try {
            tOpt = (Optional<T>) repository.findById(t.getClass().getField("id").getInt(t));
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
            Logger.getLogger(BaseService.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (tOpt!=null && tOpt.isPresent()) {
            t = tOpt.get();
        }
    }

    repository.save(convertToBeans(r));
    }

public abstract T convertToBeens(R dto);
}