动态选择 Spring Data JPA 存储库
我对 Java 中的类型转换和 Spring 概念很陌生。
我有以下实体:
@MappedSuperclass
public class Fish {}
@Entity
public class Whale extends Fish{
// There is no other property here..
}
@Entity
public class Shark extends Fish{
// There is no other property here..
}
我已经为这些实体创建了相应的存储库:
public interface WhaleRepository extends CrudRepository<Whale, String> {}
public interface SharkRepository extends CrudRepository<Whale, String> {}
我有一个控制器,根据端点我想保存数据..
@RestController
public class FishController {
@ResponseBody
@RequestMapping(value = "{fish-type}")
public ResponseEntity<Long> create(@PathVariable("fish-type") String fishType, @RequestBody Fish fish){
if(fishType.equals("whale"}{
// Error: The method save(S) in the type CrudRepository<Whale,Long> is not applicable for the arguments (Fish)
new WhaleRepository().save(fish);
}
else if(fishType.equals("shark"}{
// Error: The method save(S) in the type CrudRepository<Shark,Long> is not applicable for the arguments (Fish)
new SharkRepository().save(fish);
}
}
}
有没有一种方法可以动态选择存储库并保留数据。
I am new to the concept of type casting and Spring in Java.
I have below entities:
@MappedSuperclass
public class Fish {}
@Entity
public class Whale extends Fish{
// There is no other property here..
}
@Entity
public class Shark extends Fish{
// There is no other property here..
}
I have created corresponding repositories for these entity:
public interface WhaleRepository extends CrudRepository<Whale, String> {}
public interface SharkRepository extends CrudRepository<Whale, String> {}
I have a single controller where depending on the endpoint I want to save the data ..
@RestController
public class FishController {
@ResponseBody
@RequestMapping(value = "{fish-type}")
public ResponseEntity<Long> create(@PathVariable("fish-type") String fishType, @RequestBody Fish fish){
if(fishType.equals("whale"}{
// Error: The method save(S) in the type CrudRepository<Whale,Long> is not applicable for the arguments (Fish)
new WhaleRepository().save(fish);
}
else if(fishType.equals("shark"}{
// Error: The method save(S) in the type CrudRepository<Shark,Long> is not applicable for the arguments (Fish)
new SharkRepository().save(fish);
}
}
}
Is there a way by which I can dynamically pick the repository and persist the data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,你可以。
首先,您必须创建一个抽象实体和存储库。
其次,您需要在
Jackson
中使用继承来在请求中发送通用实体。例如,类似这样的内容:
FishRepository
类:Fish
类:Controller
类:现在您需要在请求中发送
fishType
。例如:参考文献:
Spring @RequestBody 继承
具有抽象类/继承的 Spring Data Rest Repository
Yes you can.
Firstly, you have to create a abstract entity and repository.
Secondly, you need to use inheritance in
Jackson
to send generic entity in request.For example, something like this:
FishRepository
class:Fish
class:Controller
class:Now you need to send the
fishType
inside your request. E.g:References:
Spring @RequestBody inheritance
Spring Data Rest Repository with abstract class / inheritance