Search code examples
javasqljpajpql

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


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', '[email protected]',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();

Solution

  • 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.