Hibernate、Spring JPA、ManyToMany 设置查询:无法确定适当的实例化策略 - 未找到匹配的构造函数

问题描述 投票:0回答:1

我在

@ManyToMany
Dog
之间有
Command
关系。我试图使用
Query
获取所有狗及其命令(为了排除获取
Dog
类中的任何其他数据),但是它失败了,尽管构造函数有效:

Dog.java:

@Entity(name = "dogs")
public class Dog  {
    @Id
    @SequenceGenerator(name = "dog_sequence",
        sequenceName = "dog_sequence",
        allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
        generator = "dog_sequence")
    private Long id;

    @Column(unique = true)
    private String name;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name = "dog_command",
        joinColumns = {@JoinColumn(name = "dog_id")},
        inverseJoinColumns = {@JoinColumn(name = "command_id")})
    private Set<Command> commands;

    public Dog() {}
    
    public Dog(Long id, String name, Set<Command> commands)  {
        this.id = id;
        this.name = name;
        this.commands = commands;
    }
...

Command.java:

@Entity(name = "commands")
public class Command  {
    private enum CommandEnum  {SIT, JUMP, VOICE}

    @Id
    @SequenceGenerator(name = "command_sequence",
        sequenceName = "command_sequence",
        allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
        generator = "command_sequence")
    private Long id;

    @Enumerated(EnumType.STRING)
    @Column(name = "command", unique = true)
    private CommandEnum command;
...

DogRepository.java:

public interface DogRepository extends JpaRepository<Dog, Long> {
    
    @Query("select new com.example.demo.story.model.Dog(d.id, d.name, d.commands) from dogs d inner join d.commands c")
    List<Dog> findDogsWithCommands();
    
}

DogController.java:

@RestController
@RequestMapping(path = "api/dog")
public class DogController {
    private DogRepository dogRepository;

    @Autowired
    public DogController(DogRepository dogRepository) {
        this.dogRepository = dogRepository;
    }

    @GetMapping("all")
    @CrossOrigin
    public List<Dog> getStoriesNamesPictures()  {
        List<Dog> dogs = this.dogRepository.findDogsWithCommands();
        
        return dogs;
    }
}

我明白了

java.lang.IllegalStateException:无法确定适当的 实例化策略 - 未找到匹配的构造函数以及一个或多个 参数没有为 bean 注入定义别名

错误。

我不能只使用

dogRepository.findAll()
,因为
Dog
类可能有更多我不想从数据库(从其他连接表)中提取的数据。

在原始

SQL
中,执行此操作只需单个
SQL
查询即可:

SELECT id, name, command FROM dogs d INNER JOIN commands c ON d.id = c.dog_id;

Spring Data 中似乎无法做到?这是否意味着我必须在

SQL
内触发第二个
DogController
查询?

处理这种情况的最佳方法是什么?

java spring hibernate spring-data-jpa spring-data
1个回答
0
投票

试试这个

public interface DogWithCommands {
    Long getId();

    String getName();

    Set<Command> getCommands()
}

@Query("SELECT d.id, d.name, d.commands FROM Dog d INNER JOIN d.commands")
List<DogWithCommands> findDogsWithCommands();
© www.soinside.com 2019 - 2024. All rights reserved.