Spring EntityManager已关闭

时间:2017-02-14 16:59:54

标签: java spring dao

我想搜索非唯一的用户名。我在DAO中实现了以下代码,它给出了错误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();
}

查询:@NamedQuery(name="Client.CheckUsername", query="SELECT c.username FROM Client c WHERE c.username = :username")

服务:

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

如何解决此问题?

1 个答案:

答案 0 :(得分:3)

首先,您需要更改查询,因为它返回的是字符串,而不是对象。 findByUsername函数返回对象。

@NamedQuery(name="Client.CheckUsername", query="SELECT c FROM Client c WHERE c.username = :username")

服务:

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

我强烈建议您使用DEBUG功能,而不是在函数中打印变量。