编程语言
首页 > 编程语言> > java-使用CrudRepository从View获取数据

java-使用CrudRepository从View获取数据

作者:互联网

对于这个问题,我不是在寻找解决方案,而是在寻找可以使自己前进的方向,因此不共享任何代码.

我正在准备一个REST API,并且在本地设置了postgresql数据库,该数据库具有2个表和这2个表中的一个视图.

通常,当我想从数据库中获取任何数据时,我会使用以下代码(为清楚起见):

DataRepository类:

public interface DataRepository extends CrudRepository<Data, String>{}

DataService类:

@Service
public class DataService {
    @Autowired
    private DataRepository repo;
    public Data getData(String id){
        return repo.findById(id).orElse(null);
    }
}

DataController类:

@RestController
public class DataController{
    @Autowired
    private DataService service;
    @RequestMapping("/{id}")
    public Data getData(String id){
        return service.getData(id);
    }
}

资料类别:

@Entity
public class Data{
    @Id
    private String id;
    private String name;

    //respective getter and setter methods
}

现在,我想从视图中检索数据,那么应该采取什么方法呢?

我们是否应该使用创建Model,Service,Ctonroller和Repository类的相同方法?

我们可以使用CrudRepository来实现吗?

我在很多地方搜索过,但没有发现任何有用的信息.

让我知道是否有人对此有任何线索.

解决方法:

CrudRepository的读取方法在视图上应该可以正常工作.对于写方法,视图需要为updatableenter link description here.

如果您只想读取而不是写入存储库,则可以通过复制CrudRepository的源代码并删除所有写入方法来创建ReadOnlyRepository.

请注意,JPA仍将尝试保留对托管实体所做的更改.
为了避免这种情况,并且避免进行脏检查,如果您使用的是Hibernate,可以拨打mark your entities as immutable.

标签:spring-boot,rest,spring-data-jpa,java,spring-mvc
来源: https://codeday.me/bug/20191211/2106361.html