我尝试通过创建一个简单的Eclipse动态Web项目来使用JSP。
我制作了一个基本的JSP和一个为HttpServlet创建参数化请求的表单。这个servlet应该只使用实体bean将数据存储到数据库中。
我通过注释使用了映射。
这是我的jsp的调用部分:
<form action="persistencedemo" method="get">
<input type="submit" name="submit" value='ok'/>
<input type="hidden" name="firstName" value='<jsp:getProperty property="firstname" name="newCustomer"/>' />
<input type="hidden" name="lastName" value='<jsp:getProperty property="lastname" name="newCustomer"/>' />
</form>
...这是我的bean的主要部分:
@Entity
@Table(name="CUSTOMERS")
public class CustomerBean implements Serializable {
@Id
@Column(name = "CUSTOMER_ID")
private Long id;
@Column(name = "FIRST_NAME")
private String firstname;
@Column(name = "LAST_NAME")
private String lastname;
public CustomerBean() {
this.firstname = "";
this.lastname = "";
}
// Getters & Setters
现在 - 终于 - 这是我非常简单的servlet:
@WebServlet(name="PersistenceDemo", urlPatterns = {"/persistencedemo"})
public class PersistenceDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
@PersistenceUnit
private EntityManagerFactory entityManagerFactory;
@Resource
private UserTransaction userTransaction;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
EntityManager em = entityManagerFactory.createEntityManager();
CustomerBean c1 = new CustomerBean();
CustomerBean c2 = new CustomerBean();
c1.setFirstname("My");
c1.setLastname("Self");
c1.setId(3L);
c2.setId(4L);
c2.setFirstname(req.getParameter("firstName"));
c2.setLastname(req.getParameter("lastName"));
try {
userTransaction.begin();
em.persist(c1);
em.persist(c2);
userTransaction.commit();
}
catch (Exception e) {
e.printStackTrace();
}
resp.getWriter().print("Updated database!");
}
}
[更新] 我的persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="hello-world" transaction-type="RESOURCE_LOCAL">
<class>com.jpa.PersistenceDemo</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/customerdb" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="customeruser" />
<property name="javax.persistence.jdbc.password" value="customerpass" />
</properties>
</persistence-unit>
</persistence>
问题:我链接了mySQL连接器并创建了表,但是当我调用 entityManagerFactory.createEntityManager()时,它一直崩溃并显示错误消息:
Unable to retrieve EntityManagerFactory for unitName null
嗯,除了我应该使用另一个结构将模型(bean)与视图(jsp)分开的事实:
这里有什么问题?
答案 0 :(得分:0)
您的persistence.xml文件位于何处?
也许项目结构不正确? EJB是否属于自己独立的部分?尝试打包项目的各个部分using CDI或Enterprise Application。
尝试在您编写Java的任何程序中创建“新企业项目”,如果您不确定我在说什么,请查看自动生成的内容。