Reputation: 371
I want to search for username which is not unique. I implemented below code in DAO and it gives error HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalStateException: EntityManager is closed
.
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void save(Client client) {
entityManager.persist(client);
}
public Client findByUsername(String username) {
Query query = entityManager.createNamedQuery("Client.CheckUsername");
query.setParameter("username", username);
return (Client) query.getSingleResult();
}
Query: @NamedQuery(name="Client.CheckUsername", query="SELECT c.username FROM Client c WHERE c.username = :username")
Service:
@Autowired
ClientDAO clientDAO;
public Client findClientByUsername(String username){
System.out.println("findclientbyusername: " + username);
return clientDAO.findByUsername(username);
}
public boolean isUsernameUnique(String username) {
Client client = findClientByUsername(username);
System.out.println("isusernameunique?: " + username);
System.out.println(client);
return (client == null || ((username != null) && client.getUsername() == username));
How can I fix this issue?
Upvotes: 2
Views: 4989
Reputation: 1294
First of all you need to change your query because it is returning a string, not an object. findByUsername
function returns object.
@NamedQuery(name="Client.CheckUsername", query="SELECT c FROM Client c WHERE c.username = :username")
Service:
@Autowired
ClientDAO clientDAO;
public Client findClientByUsername(String username){
return clientDAO.findByUsername(username);
}
public boolean isUsernameUnique(String username) {
Client client = findClientByUsername(username);
return (client == null || ((username != null) && client.getUsername() == username));
dao:
public Client findByUsername(String username) {
Query query = entityManager.createNamedQuery("Client.CheckUsername");
query.setParameter("username", username);
return (Client) query.getSingleResult();
}
And I strongly recommend you to use DEBUG feature instead of printing variables out in the functions.
Upvotes: 3