Question

im new to JPA and Servlets. I'm trying to create Student Entity and insert that to my DB using a Servlet. there are no errors in the code. When I go to the Servlet, it worked without errors in the Browser. But the values are not inserted to my DB.

Student Entity:-

@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 + " ]";
}

}

my 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);
    }
}

my Objective:-

  • Create id as unique and auto increment.

UPDATED

persistence.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>
Was it helpful?

Solution

Check that you have a JTA persistence unit (in persistence.xml) and then call em.joinTransaction() after beginning the transaction OR call EntityManager em = emf.createEntityManager(); after beginning the transaction.

OTHER TIPS

You will require transaction associated with the operation. There are 2 ways to solve this problem - 1. Use Spring Transaction Add this annotation

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>

And in your DAO class annotate your methods with @Transactional

  1. Use Spring AOP Give advice on your methods -

Configure your advice

<aop:config>
        <aop:pointcut id="appControllerTransactionPointCuts"
            expression="execution(* package.structure..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="appControllerTransactionPointCuts" />
    </aop:config>

Now your DAO will run in a transaction

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top