gpt4 book ai didi

java - 使用 @DiscriminatorValue 的多个对象的单个存储库

转载 作者:行者123 更新时间:2023-11-30 01:51:20 24 4
gpt4 key购买 nike

我有几个实体与具有一个基类的 @DiscriminatorValue 共享同一个数据库表:

@Entity(name = "base_details")
@DiscriminatorColumn(name = "type")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Getter
@Setter
public abstract class BaseDetails {

@Id
@Column(name = "identifier")
private String identifier;

@Column(name = "item_type")
@Enumerated(EnumType.STRING)
private Type type;

}

@Entity
@DiscriminatorValue("ONE")
@Getter
@Setter
public class FirstDetails extends BaseDetails {
...
}

@Entity
@DiscriminatorValue("TWO")
@Getter
@Setter
public class SecondDetails extends BaseDetails {
...
}

这工作正常,但我遇到了一个问题,因为有太多单独的存储库:

@Repository
public interface OneDetailsRepository extends JpaRepository<OneDetails, String> { ... }

等等

有没有办法拥有一个可以与所有派生实体一起使用的单个存储库(例如BaseDetailsRepository)?

编辑:我正在寻找的是这样的:

@Repository
public interface BaseDetailsRepository extends JpaRepository<? extends BaseDetails, String> {
OneDetails findOne(String identifier);
SecondDetails findOne(String identifier);
}

最佳答案

您可以执行以下操作:

存储库:BaseDetailsRepo.java

@Repository
public interface BaseDetailsRepo extends JpaRepository<BaseDetails, String>{
//make the return according to you ..it shouldn't be list....

@Query("FROM SecondDetails AS bd WHERE bd.identifier=:identifier")
public List<SecondDetails> getSecondDetailsByIdentifier(@Param("identifier") String identifier);

@Query("FROM FirstDetails AS bd WHERE bd.identifier=:identifier")
public List<FirstDetails> getFirstDetailsByIdentifier(@Param("identifier") String identifier);
}

Controller :DemoController.java

@Controller
public class DemoController {

@Autowired
private BaseDetailsRepo baseDetailsRepo;


@GetMapping(value="/test")
public ResponseEntity test(){

FirstDetails fd = new FirstDetails();
fd.setIdentifier("fd1-demo");

FirstDetails fd1 = new FirstDetails();
fd1.setIdentifier("fd2-demo");


SecondDetails sd = new SecondDetails();
sd.setIdentifier("sd1-demo");
baseDetailsRepo.save(fd);
baseDetailsRepo.save(fd1);
baseDetailsRepo.save(sd);

return new ResponseEntity("Success",HttpStatus.OK);
}


@GetMapping(value="/test/second/{id}")
public ResponseEntity getSecondDetails(@PathVariable String id){
return new ResponseEntity(baseDetailsRepo.getSecondDetailsByIdentifier(id),HttpStatus.OK);
}


@GetMapping(value="/test/first/{id}")
public ResponseEntity getFirstDetails(@PathVariable String id){
return new ResponseEntity(baseDetailsRepo.getFirstDetailsByIdentifier(id),HttpStatus.OK);
}
}

输出

Test

关于java - 使用 @DiscriminatorValue 的多个对象的单个存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55947361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com