REST Service with NetBeans JPA - java

I have some difficulties with my first experiments with Web Applications.
I’m using
jdk15.0.1
NetBeans 12.0
MySQL 5.7.19
Payara Server 5.201
Windows 10 build 19041.685
When I create a project Web Application ( Java with Maven > Web Application ), I write my Entity Class, but when I try to generate Persistence unit it does not allow me to use the JTA.
Book.java
#XmlRootElement
#Entity
#NamedQueries({
#NamedQuery(name = "Book.findAll", query = "SELECT d FROM Book d")
})
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String author;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
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 Book)) {
return false;
}
Book other = (Book) 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 "com.mycompany.test201.Book[ id=" + id + " ]";
}
}
I add New>RESTful Web Services from Patterns...
BookResource.java
#RequestScoped
#Path("book")
public class BookResource {
#PersistenceContext(unitName = "test201pu")
private EntityManager em;
// #Context
// private UriInfo context;
/**
* Creates a new instance of BookResource
*/
public BookResource() {
}
#POST
#Transactional
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void addBook(#FormParam("aut")String autr, #FormParam("titl")String til) {
Book b=new Book();
b.setAuthor(autr);
b.setTitle(til);
em.persist(b);
}
/**
* Retrieves representation of an instance of com.mycompany.test201.BookResource
* #return an instance of java.lang.String
*/
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Book> getXml() {
Query q=em.createNamedQuery("Book.findAll", Book.class);
return q.getResultList();
}
/**
* PUT method for updating or creating an instance of BookResource
* #param content representation for the resource
*/
#PUT
#Consumes(MediaType.APPLICATION_XML)
public void putXml(String content) {
}
}
I am forced to correct by hand the XML from
transaction-type="RESOURCE_LOCAL" to transaction-type="JTA" .
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="test201pu" transaction-type="JTA">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test201?zeroDateTimeBehavior=CONVERT_TO_NULL"/>
<property name="javax.persistence.jdbc.user" value="piero"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="my_password"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Also the checkbox "Include All Entity Classes in ... Module" is always disabled (and the same the other checkbox “Use Java Transaction APIs”)
Finally when I try some transaction, obviously using like JDBC a connection to database MySQL, there’s no tables in database, so I don’t know where the data was stored.

Related

How can I insert new row in a table using Hibernate?

I'm trying to understand JPA/Hibernate, I'm able to create new database but I don't understand how insert new row in my
database.
This is the code:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String adress;
private String phoneNumber;
public void setName(String name) {
this.name = name;
}
public void setAdress(String adress) {
this.adress = adress;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public String getAdress() {
return adress;
}
public String getPhoneNumber() {
return phoneNumber;
}
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 Person)) {
return false;
}
Person other = (Person) 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 "entinty.Person[ id=" + id + " ]";
}
}
The class that create the database is:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
public class Main {
public static void main(String args[]) {
Person p = new Person();
p.setName("xxx");
p.setAdress("yyy");
p.setPhoneNumber("zzz");
EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("testPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try {
em.persist(p);
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
}
em.close();
emf.close();
}
}
At this point I have a table with one row (with written "xxx-yyy-zzz"). How can I add new row? Creating new Person doesn't work because it creates new table... I only find solution using Session and SessionFactory but I'm not able to use it, because I can't understand how generate a hibernate.cfg.xml (and in general how to create a session object).
Is There a solution using only EntityManager? Or how can I generate/write a hibernate.cfg.xml file? Is there a way to generate automatically it using netbeans?
EDIT: this is my persistence.xml file. Where do I have to put the ? I put it in the *** zone but it doesn't work...
<?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="testPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>test.Person</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/stackoverflow?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="leonida95."/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
*****
</properties>
</persistence-unit>
</persistence>
Inside your Persistence Unit file you'll have something like
<properties>
<property name="hibernate.connection.url" value="..." />
<property name="hibernate.connection.driver_class" value="..."/>
...
</properties>
To create tables when the EntityManagerFactory is constructed, just add
<property name="hibernate.hbm2ddl.auto" value="create" />
Your code works fine.
You can call persist as many times as you want, and it will add rows to the target table.
em.persist(person1);
em.persist(person2);
...
persist does not create a table.

JavaEE JPA returning versions of old data

We are building a REST application using JPA which we have trouble getting to work properly.
The issue is that when doing updates or adding items jpa selects starts returning multiple versions of the changed. For example if Item contains A and is changed to B then changed to C, select queries will return A first run, B second, C third, A fourth etc. Sometimes it wont show directly but holding down f5 on the browser for GET items resource then changing the data always generates this problem.
Ive created a clean sample project which demonstrates this. We use Glassfish 4.1.0 (since there were som other issues with 4.1.1).
Created mysql database 'testdb' Created a table 'item' containing two VARCHAR(45) fields, 'firstName' and 'lastName'.
Created a new maven project based on 'javaee7-essentials-acrhetype'. (https://github.com/AdamBien/javaee7-essentials-archetype)
Added datasource in intellij and generated an Entity bean for this Item entity. Adjusted persistence.xml to include username and password.
Created a simple DTO / Pojo class to receive the PUT data.
Created an ItemResource class.
All in all 4 classes and persistence.xml + pom.xml
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test.server</groupId>
<artifactId>testdb</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
</dependencies>
<build>
<finalName>testdb</finalName>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
</project>
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
<persistence-unit name="LocalUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>test.server.entities.ItemEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/testdb"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="abc123" />
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
ItemDTO
public class ItemDTO {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
ItemEntity bean (added the namedqueries manually)
#Entity
#NamedQueries({
#NamedQuery(name = "Item.All", query = "SELECT item from ItemEntity item"),
#NamedQuery(name = "Item.Get", query = "SELECT item from ItemEntity item WHERE item.id = :id")
})
#Table(name = "item", schema = "testdb", catalog = "")
public class ItemEntity {
private Integer id;
private String firstName;
private String lastName;
#Id
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Basic
#Column(name = "firstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Basic
#Column(name = "lastName")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ItemEntity that = (ItemEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) return false;
if (lastName != null ? !lastName.equals(that.lastName) : that.lastName != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
return result;
}
}
ItemResources class
#Path("items")
public class ItemResources {
private static EntityManagerFactory emf = null;
public ItemResources() {
if(emf == null) {
emf = Persistence.createEntityManagerFactory("LocalUnit");
}
}
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getAllAccounts() {
EntityManager manager = getEntityManager();
Collection<ItemEntity> accounts = null;
try {
accounts = manager.createNamedQuery("Item.All").getResultList();
} catch(Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
return Response.ok().entity(new GenericEntity<Collection<ItemEntity>>(accounts) {}).build();
}
#PUT
#Path("{id}")
#Consumes(MediaType.APPLICATION_JSON)
public Response updateAccount(#PathParam("id") int id, ItemDTO itemDTO) {
EntityManager manager = getEntityManager();
try {
manager.getTransaction().begin();
TypedQuery<ItemEntity> query = manager.createNamedQuery("Item.Get", ItemEntity.class);
query.setParameter("id", id);
ItemEntity account = query.getSingleResult();
account.setFirstName(itemDTO.getFirstName());
account.setLastName(itemDTO.getLastName());
manager.getTransaction().commit();
} catch(Exception e) {
manager.getTransaction().rollback();
throw new RuntimeException(e);
} finally {
manager.close();
}
return Response.ok().entity("OK").build();
}
}
And the main application class (no web.xml, empty beans.xml)
#ApplicationPath("resources")
public class JAXRSConfiguration extends Application {
}
Summarized this dont work. The problem described in the beginning occurs which makes it impossible to use for anything real. Are we missing something here, shouldnt this simple example work?
We have a real application containing this issue and we have some time trying to find out why it behaves like this. We tried different ways of clearing the cache, evicting the factory, tried changing connection isolation, disabling 2ndlevel and query cache in persistence.xml but still got the same issuein the end or traded for more severe db issues. Tried on two different servers running same glassfish versions. So we are at the point if we have to roll back to pure jdbc/sql to get this working.
HOWEVER strangely i have not yet been able to reproduce the issue when deploying in intellij yet. But when deploying the .war file on any server weve tried so far the issue appears. But when officially depolyed it seems the only way to make it work would be to create a new fctory instance for each request then close it when done. Which seems extremely wasteful.
If anyone could help us solve this and thus avoid alot of refactoring we would be forever greatful :) Are we missing something vital that is needed for this to work?

EntityManager doesn't save entity to MySQL database table

I use JPA MySQL to execute queries to database , but when I try to persists some entity no row is added to the table
Here is persistense.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/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">
<persistence-unit name="avtoparki" transaction-type="RESOURCE_LOCAL">
<description>
Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Entities.City</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/world" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="tauren993" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<!-- <property name="hibernate.hbm2ddl.auto" value="create" /> -->
</properties>
</persistence-unit>
</persistence>
here is entity class:
#Entity
public class City {
#Id
//#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
int id;
#Column(name="Name")
String name;
#Column(name="CountryCode")
String CountryCode;
#Column(name="District")
String District;
#Column(name="Population")
int Population;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryCode() {
return CountryCode;
}
public void setCountryCode(String countryCode) {
CountryCode = countryCode;
}
public String getDistrict() {
return District;
}
public void setDistrict(String district) {
District = district;
}
public int getPopulation() {
return Population;
}
public void setPopulation(int population) {
Population = population;
}
and here is code:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("avtoparki");
EntityManager em = emf.createEntityManager();
City city = new City();
city.setCountryCode("Georgia");
city.setDistrict("AVOIE");
city.setName("Tbilisi");
city.setId(1);
em.persist(city);
em.close();
System.out.println("SAVED");
when I execute there is no error it just doesn't save it to table (the city table exists and the schema is the same
Seems to me, that you are missing a transaction. Try to save your city-object with following code:
private void save (City city, EntityManagerFactory emf) {
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
em.persist( city );
tx.commit();
} catch( RuntimeException ex ) {
if( tx != null && tx.isActive() ) tx.rollback();
throw ex;
} finally {
em.close();
}
}
I would try an explicit flush em.persist(), em.flush(), em.close(). Just to verify.
You should create a Default no-args constructor
public City() { }
Hibernate uses reflection to create objects

JPA 2.0 not persisting into MySQL

I am new to JPA 2.0 API and I am trying to have a start up with JPA to Mysql transaction but I am enable to do so. And I am not getting any errors.
package com.testjpa.demo;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the employee database table.
*
*/
#Entity
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
public Employee() {
}
public Employee(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Methods to perform CRUD operations
package com.testjpa.demo;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public class EmployeeService {
/**
* #param args
*/
protected EntityManager em;
public EmployeeService(EntityManager em) {
this.em = em;
}
public Employee findEmployee(int id) {
return em.find(Employee.class, id);
}
public Employee createEmployee(int id, String name) {
Employee emp = new Employee(id);
emp.setName(name);
return emp;
}
public void removeEmployee(int id) {
Employee emp = findEmployee(id);
if (emp != null) {
em.remove(emp);
}
}
public List<Employee> findAllEmployees() {
TypedQuery<Employee> query = em.createQuery("select e from Employee e",
Employee.class);
return query.getResultList();
}
}
Test Class to persist the data into MysQL
package com.testjpa.demo;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EmployeeTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("JPADemo");
EntityManager em = emf.createEntityManager();
EmployeeService service = new EmployeeService(em);
// create and persist an employee
em.getTransaction().begin();
Employee emp = service.createEmployee(2, "John Doe");
em.getTransaction().commit();
System.out.println("Persisted " + emp);
emp = service.findEmployee(2);
System.out.println("Found " + emp);
}
}
I will really appreciate suggestions as i am totally new to this API
Also Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/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">
<persistence-unit name="JPADemo" transaction-type="RESOURCE_LOCAL">
<class>com.testjpa.demo.Employee</class>
<properties>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/world"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="123456"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
In your createEmployee method you are instantiating a new Employee POJO but you never persist it with the EntityManager, so Hibernate is not aware of it. Try adding:
em.persist(emp);

JPA reads but doesn't persists

My Java Web App reads data from database but when I try to write something, JPA says ok, but the database does not change. I call "merge" method and the data are not being saved on database, only in memory. I can do a SELECT direct into database and see old data. But the Java Console does not throw any Exception as you can see above.
Java Console:
INFO: [EL Finest]: 2011-10-14 15:02:41.847--UnitOfWork(13027895)--Thread(Thread[http-thread-pool-8080-(6),10,Grizzly])--Merge clone with references user1
Change Password's method that is being called:
public static User changePassword(String username, String oldPassword, String newPassword){
User user = userFacade.find(username);
if(user != null && user.getPassword().equals(oldPassword)){
user.setPassword(newPassword);
userFacade.edit(user); // supposed to save the new password on database, but it's not
// at this point, the user has a new password on memory, but on database the password is still the old one
return user;
}
return null;
}
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/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">
<persistence-unit name="APP1PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.company.User</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/app1"/>
<property name="javax.persistence.jdbc.password" value="12345"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
User.java:
#Entity
#Table(name = "user")
#Cache (
type=CacheType.NONE
)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
private String username;
#Basic(optional = false)
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserFacade.java
public class UserFacade {
private EntityManagerFactory emf = Persistence.createEntityManagerFactory("APP1PU");
private EntityManager em;
protected EntityManager getEntityManager() {
if( em == null ){
em = emf.createEntityManager();
}
return em;
}
public void create(User entity) {
getEntityManager().persist(entity);
}
public void edit(User entity) {
getEntityManager().merge(entity);
}
public void remove(User entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public User find(Object id) {
return getEntityManager().find(entityClass, id);
}
}
Anyone can figure why this behavior? Or has some suggestion of a test I could do?
Thanks in advance!
Try entityManager.flush() after a write operation. Or start a transaction (entityManager.getTransaction().begin()) before your write operation, and then close it at the end (entityManager.getTransaction().commit())

Categories