如何在Java + hibernate + panache仓库中使用表之间的@ManyToMany关系获取列表

7gyucuyw  于 2023-05-15  发布在  Java
关注(0)|答案(1)|浏览(116)

我创建了两个实体,即Person和Message,表之间存在@ManyToMany关系。我正在使用Quarkus框架,它支持PanacheRepository和Postgres DB。我的要求是获取对应于一个人的所有消息,但我得到下面的错误:

java.lang.IllegalArgumentException:参数值[Person{...}]与预期类型[java.util.Collection(n/a)]不匹配

2023-05-12 11:19:21,285 ERROR [io.qua.ver.htt.run.QuarkusErrorHandler](executor-thread-0)HTTP请求/persons/1/messages失败,错误ID:59165c88-d7d9-470b-99f4-8ca3509f2960-1:java.lang.IllegalArgumentException:参数值[Person{id=1,name ='abhishek',age=28}]与org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54)处的预期类型[java.util.Collection(n/a)]不匹配
任何建议/意见都将是非常有益的。
这些实体是:

@Entity
public class Message {
    @Id
    @GeneratedValue
    @Column(name = "message_id")
    Long id;

    @Column
    String messageBody;

    @JsonManagedReference
    @ManyToMany
    private List<Person> person;
    ..................
    ..................

}

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "person_id")
    private Long id;

    @Column(name="person_name")
    private String name;

    @Column
    private int age;

    @JsonBackReference
    @ManyToMany(mappedBy = "person", fetch = FetchType.LAZY)
    private List<Message> messageList;
    .............................
    .............................
}

存储库类:

@ApplicationScoped
public class MessageRepository implements PanacheRepository<Message> {
}

@ApplicationScoped
public class PersonRepository implements PanacheRepository<Person> {
}

资源类:

@Path("/persons")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class PersonResource {
    @Inject
    PersonRepository personRepository;

    @Inject
    MessageRepository messageRepository;

    @GET
    @Path("/{userId}/messages")
    public Response listAllMessagesOfAUser(Long userId) {
        Person person = personRepository.findById(userId);
        
        List<Message> messagesList = messageRepository.find("person", person).list();
        
        return Response.ok(messagesList).build();
    }
.............................................
}

我首先使用userId获取person,并传递获得的person对象以获取与该person对应的消息列表。

xxhby3vn

xxhby3vn1#

我能够解决这个问题,并使用以下查询获取用户的所有消息:

List<MessageEntity> messagesList = messageRepository.find("Select m from MessageEntity m Join m.personEntity p where p.id=?1", userId).list();

相关问题