0

我正在开发 Web 项目 EJB,JPA - Hibernate 作为提供者,JBoss 6,MySql。我是 EJB、JPA 的新手。我在 servlet 中加载 ejb bean 时遇到问题。

持久性.xml

<persistence-unit name="LibraryPersistenceUnit" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:/MySqlDS</jta-data-source>
    <class>library.entity.User</class>
    <class>library.entity.Book</class>
    <properties>
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
    </properties>

</persistence-unit>

UserFacade.java

@Local
public interface UserFacade {
    User findUserByLoginAndPassword(String login, String password);

   /* List<User> getClients();

    void returnBooks(long userId, long[] ids);

    void takeBooks(long userId, long[] ids);*/
}

UserFacadeImpl.java

package library.facades.impl;

import library.dao.impl.UserDAO;
import library.entity.User;
import library.facades.interfaces.UserFacade;

import javax.ejb.EJB;
import javax.ejb.Stateless;

@Stateless
public class UserFacadeImpl implements UserFacade {

    @EJB
    private UserDAO userDAO;

    public UserFacadeImpl() {
    }

    public User findUserByLoginAndPassword(String login, String password) {
        User user = userDAO.selectUserByLoginAndPassword(login, password);
        return user;
    }

 /*   public List<User> getListClients() {
        List<User> userList = userDAO.getClients();
        return userList;
    }

    public void returnBooks(long userId, long[] ids) {
        userDAO.returnBooks(userId, ids);
    }

    public void takeBooks(long userId, long[] ids) {
        userDAO.takeBooks(userId, ids);
    }*/
}

用户DAO.java

package library.dao.impl;


import library.dao.interfaces.GenericDAO;
import library.entity.User;

import javax.ejb.Local;
import javax.ejb.Stateless;
import java.util.HashMap;
import java.util.Map;


@Stateless
public class UserDAO extends GenericDAO {


    public UserDAO() {
        super(User.class);
    }

    public User selectUserByLoginAndPassword(String login, String password) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("login", login);
        parameters.put("password", password);
        return (User) super.findOneResult(User.SELECT_USER_BY_LOGIN_AND_PASSWORD, parameters);
    }

    /*public List<User> getClients() {
        Query namedQuery = entityManager.createNamedQuery(User.ALL_CLIENTS, User.class);
        List<User> clientsList = namedQuery.getResultList();
        return clientsList;
    }

    @Override
    public void returnBooks(long userId, long[] ids) {
        User user = entityManager.find(User.class, userId);
        for (long id : ids) {
            Book book = entityManager.find(Book.class, id);
            user.getTakenBooks().remove(book);
        }
        entityManager.merge(user);
    }

    @Override
    public void takeBooks(long userId, long[] ids) {
        User user = entityManager.find(User.class, userId);
        for (long id : ids) {
            Book book = entityManager.find(Book.class, id);
            user.getTakenBooks().add(book);
        }
        entityManager.merge(user);
    }*/
}

GenericDAO.java 包 library.dao.interfaces;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;

public abstract class GenericDAO<T> {
    private static final String LIBRARY_PERSISTENCE_UNIT = "LibraryPersistenceUnit";

    @PersistenceContext(unitName = LIBRARY_PERSISTENCE_UNIT)
    private EntityManager entityManager;

    private Class<T> entityClass;

    public GenericDAO() {
    }

    public GenericDAO(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public void save(T entity) {
        entityManager.persist(entity);
    }

    protected void delete(Object id, Class<T> classe) {
        T entityToBeRemoved = entityManager.getReference(classe, id);
        entityManager.remove(entityToBeRemoved);
    }

    public T update(T entity) {
        return entityManager.merge(entity);
    }

    public T find(int entityID) {
        return entityManager.find(entityClass, entityID);
    }

    // Using the unchecked because JPA does not have a
    // entityManager.getCriteriaBuilder().createQuery()<T> method
    @SuppressWarnings({"unchecked", "rawtypes"})
    public List<T> findAll() {
       /* CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));*/
        return null;//entityManager.createQuery(cq).getResultList();
    }

    // Using the unchecked because JPA does not have a
    // ery.getSingleResult()<T> method
    @SuppressWarnings("unchecked")
    protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
        T result = null;

        try {
            Query query = entityManager.createNamedQuery(namedQuery);

            // Method that will populate parameters if they are passed not null and empty
            if (parameters != null && !parameters.isEmpty()) {
                populateQueryParameters(query, parameters);
            }

            result = (T) query.getSingleResult();

        } catch (Exception e) {
            System.out.println("Error while running query: " + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    private void populateQueryParameters(Query query, Map<String, Object> parameters) {

        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            query.setParameter(entry.getKey(), entry.getValue());
        }
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
}

图书馆控制器

package library.controller;

import library.entity.User;
import library.facades.interfaces.UserFacade;
import library.resourses.constants.Constants;
import library.resourses.enums.Role;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class LibraryController extends HttpServlet {

    @EJB
    private UserFacade userFacade;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        performAction(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        performAction(request, response);
    }

    private void performAction(HttpServletRequest request, HttpServletResponse response) {
        String pageType = request.getParameter(Constants.PAGE_TYPE);
        if (pageType != null) {
            try {
                String page = null;
                String login = request.getParameter(Constants.USER_LOGIN);
                String password = request.getParameter(Constants.USER_PASSWORD);
                User user = userFacade.findUserByLoginAndPassword(login, password);
                if (user == null) {
                    request.getSession().setAttribute(Constants.ERROR,
                            Constants.ERROR_MESSAGE_7);
                    page = Constants.MAIN_PAGE;
                } else {
                    String namePage = user.getRole().toString().toLowerCase();
                    if (isClient(user)) {
                        request.getSession().setAttribute(Constants.CLIENT,
                                user);
                        request.getSession().setAttribute(Constants.ERROR, null);
                    } else if (isAdministrator(user)) {
                        request.getSession().setAttribute(Constants.ADMINISTRATOR,
                                user);
                        request.getSession().setAttribute(Constants.ERROR, null);
                    }
                    page = Constants.START_PAGES + namePage + Constants.END_PAGES;
                }
                RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(page);
                requestDispatcher.forward(request, response);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean isAdministrator(User user) {
        return user.getRole().equals(Role.ADMINISTRATOR);
    }

    private boolean isClient(User user) {
        return user.getRole().equals(Role.CLIENT);
    }
}

我的 userFacade 为空。你能解释一下我做错了什么吗?谢谢。

4

1 回答 1

0

问题是,不是让容器为您实例化和注入 DAO,而是您自己显式地创建 DAO 实例:

private IUserDAO dao;
public UserService() {
    dao = UserDAOImpl.getInstance();
}

对于要注入 DAO 的 EntityManager,容器必须实例化它,而不是你。用以下代码替换上面的代码,它使用依赖注入,因此还具有使您的代码可测试的优势:

@Inject
private IUserDAO dao;
于 2013-06-30T09:42:35.930 回答