Marcel Caferati
Marcel Caferati

Reputation: 174

Hibernate custom class mapping

When I fech users using this code, it works as desired.

 public List<Users> getActiveUsers(User user) {
    EntityManager entityManager = getEntityManager();
   List<User> Users = new ArrayList();
    try {
        users = entityManager.createQuery("select e from User e where  e.deleted = :deleted", User.class)
                .setParameter("deleted", false)                 
                .getResultList();
    } finally {
        entityManager.close();
    }
    return users;
}

But if I try to get only one user using th following code, it fails.

User user = (User) entityManager.createQuery("select e from User e where  e.deleted = :deleted")
                .setParameter("deleted", false)+                 
                .getSingleResult();

I can't get a mapped user, the excepction is: "can't convert com.project.model.User to com.project.model.User"

Upvotes: 0

Views: 555

Answers (2)

Marcel Caferati
Marcel Caferati

Reputation: 174

Apparently there was nothing wrong with the code. What I found out to be the problem was the same as this guy:

A classloader proplem related to spring-boot-devtools

however, the .properties file with the dozer reference did not work for me. I managed to get my code up and running by removing spring-devtools from the project. Guess I can live without live reload!

Upvotes: 1

ℛɑƒ&#230;Ŀᴿᴹᴿ
ℛɑƒ&#230;Ŀᴿᴹᴿ

Reputation: 5326

You forgot to put the class type User.class:

entityManager.createQuery("SELECT u FROM User u where  u.deleted = :deleted", User.class)
             .setParameter("deleted", false).getSingleResult();

Your method:

 public User getActiveUser(User user) {
    EntityManager entityManager = getEntityManager();      
    try {
        User user = (User) = entityManager.createQuery
                           ("SELECT u FROM User u WHERE u.deleted = :deleted", User.class)
                           .setParameter("deleted", false).getSingleResult();
    } finally {
        entityManager.close();
    }
    return user;
}
  • Look on first example, you use Users class and on second User (without S in the end)
  • You need to be care with this query, because they may be returned more than one record

Upvotes: 1

Related Questions