0

在一个servelt中,我尝试调用会话bean方法通过JPA将数据插入数据库。插入过程写在会话 bean 中。

我尝试了另一个示例,我从数据库中选择数据。“选择”效果很好。但我不知道为什么插入不起作用。

错误信息是:

HTTP 状态 500

描述:服务器遇到一个内部错误 () 阻止它完成这个请求。

异常:javax.ejb.EJBException

注意:GlassFish Server Open Source Edition 3.0.1 日志中提供了异常的完整堆栈跟踪及其根本原因。

我认为“tx.commit()”有问题,当我评论它时没有错误。但我不知道究竟是什么问题。

这是豆类

@Stateless
@LocalBean
public class testSession {

  public testSession() {
    // TODO Auto-generated constructor stub
  }

  public void insertData(){
    EntityManagerFactory emf;
    EntityManager em;

    //the Entity Class-Category
    Category cat=new Category();

    //set value
    cat.setId(5);
    cat.setName("test cat");

    //the "test" is the persist unit in persistence.xml 
    emf=Persistence.createEntityManagerFactory("test");
    em=emf.createEntityManager();

    EntityTransaction tx=em.getTransaction();
    tx.begin();
    em.persist(cat);
    tx.commit();
    em.close();
    emf.close();

  }
}

在小服务程序中

@WebServlet("/testServlet")
public class testServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

@EJB
testSession ts;

public testServlet() {
   super();
}


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out=response.getWriter();
    out.print("<html><body>");
    //call the method in the session bean to insert data
    ts.insertData();
    out.print("</body></html>");
}


}
4

2 回答 2

0

您需要通过@PersistenceContext 注入EntityManager 本身是由容器使用persistence.xml 中的信息创建的,因此要在运行时使用它,我们只需请求将其注入我们的组件之一。我们通过@PersistenceContext 做到这一点

@PersistenceContext 注释可用于任何 CDI bean、EJB、Servlet、Servlet 侦听器、Servlet 过滤器或 JSF ManagedBean。如果您不使用 EJB,则需要使用 UserTransaction 开始并手动提交事务。EntityManager 的任何创建、更新或删除方法都需要一个事务才能工作。

例子:

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
@LocalBean
public class testSession {

@PersistenceContext(unitName = "MyUNIT_PERSIS_IMPORTANT_View_THE_persistence.XML")
    private EntityManager entityManager;

  public testSession() {
    // TODO Auto-generated constructor stub
  }

  public void insertData(){
    //the Entity Class-Category
    Category cat=new Category();

    //set value
    cat.setId(5);
    cat.setName("test cat");

    entityManager.persist(cat);

  }
}

Reference
http://tomee.apache.org/examples-trunk/injection-of-entitymanager/
于 2013-04-17T04:58:58.920 回答
0

我在这个演示中使用了 maven

演示

https://mega.co.nz/#!AxtRVQzB!MdwwOXA1e_VayWgwIdxGdREhd69QDb6la0yT0mLMaKA

到 servlet 的 url

http://<HOST>/use-session-bean-to-insert-data-with-jpa/testServlet

SQL 创建

CREATE TABLE category (
id INT NOT NULL AUTO_INCREMENT, 
`name` VARCHAR(200), 
PRIMARY KEY (id));

持久性.xml

...
<persistence-unit name="test" transaction-type="JTA">
..

Java 小服务程序

import com.mycompany.ejb.testSession;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author I2B Boris
 */
@WebServlet(name = "testServlet", urlPatterns = {"/testServlet"})
public class testServlet extends HttpServlet {

    @EJB
    testSession ts;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.print("<html><body>");
        //call the method in the session bean to insert data
        ts.insertData();
        out.print("</body></html>");
    }
}

Java EJB

package com.mycompany.ejb;

import com.mycompany.entities.Category;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author I2B Boris
 */
@Stateless
@LocalBean
public class testSession {

    @PersistenceContext(unitName = "test")
    private EntityManager entityManager;

    public void insertData() {
        //the Entity Class-Category
        Category cat = new Category();

        //set value
        cat.setId(5);
        cat.setName("test cat");

        entityManager.persist(cat);

    }
}

实体

package com.mycompany.entities;

import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author I2B Boris
 */
@Entity
@Table(name = "category")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
    @NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
    @NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name = :name")})
public class Category implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @NotNull
    @Column(name = "id")
    private Integer id;
    @Size(max = 200)
    @Column(name = "name")
    private String name;

    public Category() {
    }

    public Category(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Category)) {
            return false;
        }
        Category other = (Category) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.mycompany.entities.Category[ id=" + id + " ]";
    }

}
于 2013-04-17T13:43:57.243 回答