Java EntityManager.persist()未向数据库插入值
我是JPA和Servlets的新手。我正在尝试创建学生实体,并使用Servlet将其插入数据库。代码中没有错误。当我转到Servlet时,它在浏览器中正常工作。但是这些值不会插入到我的数据库中 学生实体:-Java EntityManager.persist()未向数据库插入值,java,servlets,jpa,persistence,hql,Java,Servlets,Jpa,Persistence,Hql,我是JPA和Servlets的新手。我正在尝试创建学生实体,并使用Servlet将其插入数据库。代码中没有错误。当我转到Servlet时,它在浏览器中正常工作。但是这些值不会插入到我的数据库中 学生实体:- @Entity public class Student implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationT
@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);
}
}
公共类A扩展了HttpServlet{
@PersistenceUnit(unitName=“persistenceCheckPU”)
实体管理工厂emf;
@资源
用户事务ut;
受保护的void processRequest(HttpServletRequest请求、HttpServletResponse响应)
抛出ServletException、IOException{
setContentType(“text/html;charset=UTF-8”);
尝试(PrintWriter out=response.getWriter()){
学生=新生();
学生姓名(“约翰”);
学生年龄(22岁);
EntityManager em=emf.createEntityManager();
ut.begin();
em.persist(学生);
ut.commit();
out.println(“成功!!!”);
}捕获(SecurityException | IllegalStateException | javax.transaction.RollbackException | HeuristicMixedException | HeuristicRollbackException | SystemException | NotSupportedException ex){
Logger.getLogger(A.class.getName()).log(Level.SEVERE,null,ex);
}
}
我的目标:-
- 创建唯一且自动递增的id
<?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>
jdbc_持久性
假的
检查您是否有JTA持久化单元(在persistence.xml
中),然后在开始事务后调用em.joinTransaction()
,或者在开始事务后调用EntityManager em=emf.createEntityManager();
。<。
有两种方法可以解决此问题-
1.使用Spring事务
添加此注释
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>
现在,DAO将在事务中运行检查您是否有JTA持久化单元(在persistence.xml中),然后在开始事务后调用
em.joinTransaction()
,或者调用EntityManager em=emf.createEntityManager()
开始交易后。谢谢@AndreiI。成功了!:)我很高兴:)我发布了答案,以结束您的问题。请将其标记为已接受。
<aop:config>
<aop:pointcut id="appControllerTransactionPointCuts"
expression="execution(* package.structure..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="appControllerTransactionPointCuts" />
</aop:config>