我对 JPA 和 Servlet 还不熟悉。我正在尝试创建学生实体并使用 Servlet 将其插入到我的数据库中。代码中没有错误。当我访问 Servlet 时,它在浏览器中运行正常,没有错误。但这些值没有插入到我的数据库中。
学生实体:-
@Entity
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@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 Student)) {
return false;
}
Student other = (Student) 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 "model.Student[ id=" + id + " ]";
}
}
我的 Servlet:-
public class A extends HttpServlet {
@PersistenceUnit(unitName = "persistenceCheckPU")
EntityManagerFactory emf;
@Resource
UserTransaction ut;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Student student = new Student();
student.setName("John");
student.setAge(22);
EntityManager em = emf.createEntityManager();
ut.begin();
em.persist(student);
ut.commit();
out.println("<h2>Success!!!</h2>");
} catch (SecurityException | IllegalStateException | javax.transaction.RollbackException | HeuristicMixedException | HeuristicRollbackException | SystemException | NotSupportedException ex) {
Logger.getLogger(A.class.getName()).log(Level.SEVERE, null, ex);
}
}
我的目标:-
- 将 ID 创建为唯一且自动递增的 ID。
已更新
持久性.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="persistenceCheckPU" transaction-type="JTA">
<jta-data-source>jdbc_persistence</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
最佳答案
检查您是否有 JTA 持久性单元(在 persistence.xml
中),然后在开始事务后调用 em.joinTransaction()
或调用 EntityManager em = emf.createEntityManager();
开始事务后。
关于java - EntityManager.persist() 不将值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23489923/