Can I insert a java entity with sql INSERT statement And retrieve it with JPQL later?

StackOverflow https://stackoverflow.com/questions/20881667

  •  23-09-2022
  •  | 
  •  

Pregunta

I inserted an User object using MySql command Line. After that I try to log in with this user email. In my code there is a find method to look for users using their email field.

My problem is the user with this email is already inserted -with a SQL statement. But it cannot be fetched with using namedQuery and I am not sure why.

Can anybody give me an explanation for this?

This is my User Entity.

@Entity
public class User {

@Id
private Long id;

@Embedded
private UserCompositeKey userCompositeKey;

@Column(length = 100)
private String name;

@Column
private String password;

//getters and setters
}


@Embeddable
public class UserCompositeKey implements Serializable {
private static final long serialVersionUID = -9187448094016939417L;

@Column(length = 100, nullable = false)
private String email;

@Column(nullable = false)
private boolean expired;

//getters and setters
}

This is my SQL insert statement.

INSERT INTO User(id,name, password, email, expired) 

VALUES(1,'testUser','pasw123', 'testuser@mail.com',false);

And this is the namedQuery:

List<User>  users = entityManager.createNamedQuery("select u from User as u where u.userCompositeKey.email = :email and u.userCompositeKey.expired = false", User.class).setParameter("email", email).getResultList();
¿Fue útil?

Solución

createNamedQuery() expects the name of a named query as its first argument. You're passing it a JPQL query instead. Use createQuery() instead.

Note that your code should throw an IllegalArgumentException, with a meaningful error message indicating what the problem is. Always read and post the stack trace of the exceptions you get. Ignoring error messages is not the best way to understand why the errors occur.

Otros consejos

createNamedQuery(); excepts the name of Query, which can be in some file in classpath or can define with @NamedQuery annotation in model.

you can use entityManager.createQuery("JPQL_query") for above problem.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top