在servelt中,我尝试调用会话bean方法,通过JPA将数据插入数据库。插入过程写在会话bean中。
我尝试了另一个例子,我从DB中选择数据。 “选择”效果很好。但我不知道为什么插入不起作用。
错误信息是:
HTTP状态500
description:服务器遇到内部错误(),导致无法完成此请求。
exception:javax.ejb.EJBException
注意:GlassFish Server Open Source Edition 3。0。1日志中提供了异常的完整堆栈跟踪及其根本原因。
我认为“tx.commit()”有问题,当我评论它时,没有错误。但我不知道究竟是什么问题。
这是bean类
@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();
}
}
在servlet中
@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>");
}
}
答案 0 :(得分:0)
你需要通过@PersistenceContext注入 EntityManager本身是由容器使用persistence.xml中的信息创建的,因此要在运行时使用它,我们只需要将它注入到我们的一个组件中。我们通过@PersistenceContext
来做到这一点@PersistenceContext注释可用于任何CDI bean,EJB,Servlet,Servlet Listener,Servlet Filter或JSF ManagedBean。如果您不使用EJB,则需要手动使用UserTransaction开始并提交事务。要使EntityManager的任何create,update或delete方法起作用,都需要一个事务。
示例:
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/
答案 1 :(得分:0)
我已经将maven用于此演示
演示
https://mega.co.nz/#!AxtRVQzB!MdwwOXA1e_VayWgwIdxGdREhd69QDb6la0yT0mLMaKA
来自servlet的url这个
http://<HOST>/use-session-bean-to-insert-data-with-jpa/testServlet
SQL create
CREATE TABLE category (
id INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(200),
PRIMARY KEY (id));
的persistence.xml
...
<persistence-unit name="test" transaction-type="JTA">
..
Java Servlet
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 + " ]";
}
}