我尝试通过创建一个简单的 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)分开之外:
这里有什么问题?