postgresql 如何从数据库中获取对象字段

mm5n2pyu  于 2022-12-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(181)

我有实体:

public class Answer {
private Long id;
private Question question;
private String answer;
private boolean isRight;
}

如何从数据库中获取“isRight”字段?
在道中,我尝试了以下方法:

public Boolean isAnswerRight(Long questionId, Long answerId) {
    return entityManager.createQuery("select a from Answer where a.question.id = :questionId AND a.id = :answerId", Answer.class)
            .setParameter("questionId", questionId)
            .setParameter("answerId", answerId)
            .getSingleResult()
            .isRight();
}

但是队长说:从数据库中获取整个对象,然后立即获取字段

ajsxfq5m

ajsxfq5m1#

我觉得应该是下面这个样子。
或者,您只能从DB中选择SELECT isRight列。
此外,如果您有answerId -这应该足以唯一地标识答案,因此不需要问题ID的附加参数。

public Boolean isAnswerRight(Long answerId) {
    return entityManager.createQuery("select * from Answer a where a.id = :answerId", Answer.class)
        .setParameter("answerId", answerId)
        .getSingleResult()
        // assuming you have getter getIsRight for isRight field
        .getIsRight();
}

public Answer getAnswerById(Long answerId) {
    return entityManager.createQuery("select * from Answer a where a.id = :answerId", Answer.class)
        .setParameter("answerId", answerId)
        .getSingleResult();
}

Answer answer = getAnswerById(answerId);
// assuming you have getter for isRight field
Boolean isAnswerRight = answer.getIsRight();

相关问题