尝试使用JPA和EJB显示来自db的数据

时间:2013-05-30 14:15:13

标签: servlets jpa ejb

我尝试显示数据库中的数据,但是我得到500错误页面:javax.ejb.EJBException。我不明白为什么它不起作用。也许我的豆子错了?请帮帮我。

Glassfish日志中的警告:警告:警告:EJB5184:在EJB SearchBean上调用期间发生系统异常,方法:public java.util.Collection com.stark.logic.SearchBean.searchByNumber(int)

@Entity
@Table(name = "buy")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Buy.findAll", query = "SELECT b FROM Buy b"),
@NamedQuery(name = "Buy.findByIdBuy", query = "SELECT b FROM Buy b WHERE b.idBuy = :idBuy"),
@NamedQuery(name = "Buy.findByNumberBuy", query = "SELECT b FROM Buy b WHERE b.numberBuy = :numberBuy")})
public class Buy implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id_buy")
private Integer idBuy;
@Basic(optional = false)
@NotNull
@Column(name = "number_buy")
private int numberBuy;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "buy")
private Product product;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "buy")
private Client client;
//getters & setters

EJB BEAN:

@Stateless
@LocalBean
public class SearchBean {

@PersistenceUnit
EntityManagerFactory emf;
EntityManager em;

public Collection searchByNumber(int number){
    em = emf.createEntityManager();
    Query searchQuery = em.createNamedQuery("Buy.findByNumberBuy");
    searchQuery.setParameter("number_buy", number);
    List list = new ArrayList();
    list = searchQuery.getResultList();

    return list;
}
}

的Servlet

@EJB
private SearchBean searchBean;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws    ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html;charset=UTF-8");

    String num = request.getParameter("number");
    int number = Integer.parseInt(num);
    List list = new ArrayList();
    list = (List) searchBean.searchByNumber(number);
    Iterator it = list.iterator();
    while(it.hasNext()){
        Buy buy = (Buy) it.next();
        out.println(buy.getProduct());
    }
}

1 个答案:

答案 0 :(得分:1)

@NamedQuery和setParameter()方法中的参数名必须相等:

searchQuery.setParameter("numberBuy", number);