简体   繁体   中英

how to get object field from database

I have entity:

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

How can I get the "isRight" field from the database?

in the DaoImpl i tried this:

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();
}

but teamlead said: "you get the whole object from the database, get the field right away"

To get the "isRight" field directly from the database, you can use a SELECT statement in your JPQL query and specify only the "isRight" field in the SELECT clause.

Here is an example of how you can modify your JPQL query to achieve this:

return entityManager.createQuery("SELECT a.isRight FROM Answer a WHERE a.question.id = :questionId AND a.id = :answerId", Boolean.class)
    .setParameter("questionId", questionId)
    .setParameter("answerId", answerId)
    .getSingleResult();

This will return a Boolean object representing the value of the "isRight" field in the "Answer" entity. Note that you should also change the return type of the "isAnswerRight" method to "Boolean" to match the type of the result returned by the query.

I hope this helps. Let me know if you have any further questions or if you need more assistance.

I think it should look like below.

Alternatively, you could only SELECT isRight column from DB.

Also, if you have answerId - this should suffice to identify answer uniquely, so no need for additional parameter for question 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();
}

or

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM