Here is my persistence.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_1_0.xsd" version="1.0">
<persistence-unit name="miniDS" transaction-type="JTA">
<jta-data-source>java:/miniDS</jta-data-source>
<class>com.company.model.Ordre</class>
<properties>
<!-- Options Hibernate -->
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.default_schema" value="mini" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" />
</properties>
</persistence-unit>
My code :
// Create order
Ordre o = new Ordre();
o.setDate(req.getParameter("date"));
o.setMotif(req.getParameter("motif"));
log.info("Ordre: " + o.getDate() + " " + o.getMotif());
OrdreService os = new OrdreService();
os.persist(o);//This method is NOT even called !
// Process application flow here...
OrdreService.java :
public class OrdreService {
private OrdreDAO dao;
public OrdreService() {
dao = new OrdreDAO();
}
public void persist(Ordre o) {
System.out.println("Service persist");
dao.persist(o);
}
//...
}
OrdreDAO.java :
public class OrdreDAO {
private EntityManagerFactory emf;
private EntityManager em;
public OrdreDAO() {
emf = Persistence.createEntityManagerFactory("miniDS");
em = emf.createEntityManager();
}
public void persist(Ordre o) {
System.out.println("DAO persist");
EntityTransaction et = null;
try {
et = em.getTransaction();
et.begin();
em.persist(o);
System.out.println("commit ?");
if (et != null) {
if (et.isActive()) {
et.commit();
}
}
} catch (Throwable t) {
t.printStackTrace();
if (et != null) {
if (et.isActive()) {
et.rollback();
}
}
}
}
//...
}
OrdreService.persist is never called :\ OrdreDAO.persist too.
What's going on with JBoss ?
JBoss 5.1.0.GA
Postgresql 8.3
JPA 1
When you use '<jta-data-source>' set your transaction type to JTA in persistence.xml file:
<persistence-unit name="your_pu_name" transaction-type="JTA">
Related
Basically I am doing a Insert inside a PostgreSQL database, but since I have multiple databases I have to change the configurations based on each environment.
The thing is that I used a not really good way to do so, since everytime I do a insert, I replace all variables, which is ultra slow and definetly not a good way to achiev that.
How would I be able to do the same inserts, but having it configured while my Api started?
Here's what i'm currently doing:
package br.jus.tjba.dje.local.service;
import br.jus.tjba.dje.local.entity.Conteudo;
import br.jus.tjba.dje.local.repository.ConteudoRepository;
import br.jus.tjba.tjfw4.core.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
#Service
public class ConteudoService extends AbstractService {
#Autowired
private ConteudoRepository conteudoRepository;
public EntityTransaction insertInDb(String something, String somethingElse) {
Map<String, String> env = System.getenv();
Map<String, Object> configOverrides = new HashMap<>();
// Here I change my persistance.xml configs
for(Map.Entry<String, String> entry: env.entrySet()) {
if (entry.getKey().contains("DATABASE_URL")) {
configOverrides.put("javax.persistence.jdbc.url", env.get(entry.getValue()));
} else if (entry.getKey().contains("DATABASE_USER")) {
configOverrides.put("javax.persistence.jdbc.user", env.get(entry.getValue()));
} else if (entry.getKey().contains("DATABASE_PASSWORD")) {
configOverrides.put("javax.persistence.jdbc.password", env.get(entry.getValue()));
}
}
// Cria um factory dando override nas variáveis.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("default", configOverrides);
EntityManager conteudoManager = factory.createEntityManager();
Query query = conteudoManager.createNativeQuery("INSERT INTO something(" +
"SOMETHING," +
"SOMETHING_ELSE)" +
" VALUES (" +
":something," +
":somethingElse)");
conteudoManager.getTransaction().begin();
query.setParameter("something", something);
query.setParameter("somethingElse", somethingElse);
query.executeUpdate();
return conteudoManager.getTransaction();
}
public Conteudo getContent() {
return conteudoRepository.getContent();
}
}
Also my persistance.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="default" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="javax.persistence.jdbc.url" value="url" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="javax.persistence.jdbc.user" value="login" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
I am developing an application with REST services. I am using dependency injection to, among other things, inject EntityManagerFactory. I have a heavy process where I want to use threads, but it is giving me a deadlock when using EntityManager. The code:
Note: All code has been simplified and renamed classes to explain the problem
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="mypersistenceunit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!-- Entities -->
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.event.merge.entity_copy_observer" value="allow" />
<property name="hibernate.connection.autocommit" value="false"/>
</properties>
</persistence-unit>
</persistence>
applicationContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
"
default-autowire="byName">
<context:property-placeholder location="classpath:database.properties"/>
<bean id="logDao" class="my.package.example.dao.LogDao">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="extractDataDao" class="my.package.example.source.ExtractDataDao">
<property name="completeDatabaseModel" ref="completeDatabaseModel"/>
</bean>
<bean id="completeDatabaseModel" class="my.package.example.source.CompleteDatabaseModel">
<property name="logDao" ref="logDao" />
</bean>
<bean id="fill" class="my.package.example.services.impl.FillDatabaseServiceImpl">
<property name="extractDataDao" ref="extractDataDao" />
</bean>
<!-- Configuracion de acceso a base de datos -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="persistenceUnitName" value="mypersistenceunit"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>
<bean id="myDataSource" parent="dataSource">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
FillDatabaseServiceImpl.java:
public class FillDatabaseServiceImpl implements FillDatabaseService {
private ExtractDataDao extractDataDao;
private final static Gson gson = new Gson();
#Override
public Response start() {
ResultDto resultDto = new ResultDto();
Thread thread = new Thread(this.extractDataDao);
thread.start();
resultDto.setData("Process has started");
return Response.ok(gson.toJson(resultDto)).build();
}
public void setExtractDataDao(ExtractDataDao extractDataDao) {
this.extractDataDao = extractDataDao;
}
}
ExtractDataDao.java:
public class ExtractDataDao implements Runnable {
private CompleteDatabaseModel completeDatabaseModel;
#Override
public void run() {
// Very simplifed class
int numThreads = 5;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
for (int j = 0; j < numThreads; j++) {
executor.execute(this.completeDatabaseModel);
}
}
public void setCompleteDatabaseModel(CompleteDatabaseModel completeDatabaseModel) {
this.completeDatabaseModel = completeDatabaseModel;
}
}
CompleteDatabaseModel.java
public class CompleteDatabaseModel implements Runnable {
private EntityManagerFactory entityManagerFactory;
private LogDao logDao;
#Override
public void run() {
// Very simplified class
EntityManager entityManager = null;
try {
entityManager = this.entityManagerFactory.createEntityManager();
...
this.logDao.insertLog("Test message", CATEGORY);
...
this.getCountry(entityManager, "country")
} finally {
entityManager.close();
}
}
private synchronized Country getCountry(final EntityManager entityManager, String strCountry) {
Country country = Country.getCountryByCountry(entityManager, strCountry);
if (country == null) {
country = ImdbToMovieDatabase.convert(strCountry, Country.class);
entityManager.getTransaction().begin();
entityManager.persist(country);
entityManager.getTransaction().commit();
country = Country.getCountryByCountry(entityManager, strCountry);
}
return country;
}
public void setLogDao(final LogDao logDao) {
this.logDao = logDao;
}
}
And the classes that provoke deadlock:
LogDao.java:
public class LogDao {
private EntityManagerFactory entityManagerFactory;
public void insertLog(final String message, final Category.CategoryName categoryName) {
Log log = new Log();
EntityManager entityManager = this.entityManagerFactory.createEntityManager();
try {
entityManager.getTransaction().begin();
Category category = Category.getCategoryByName(entityManager, categoryName.name());
log.setCategory(category);
log.setLog(message);
entityManager.persist(log); // // Cause of deadlock in Thread-1 (for example)
entityManager.getTransaction().commit();
} catch (Exception e) {
logger.error("Error persisting log [" + message + "]", e);
entityManager.getTransaction().rollback();
} finally {
if (entityManager != null) {
entityManager.close();
}
}
}
public void setEntityManagerFactory(final EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
}
Entity.java:
public static Country getCountryByCountry(final EntityManager entityManager, final String strCountry) {
Country country = null;
try {
TypedQuery<Country> typedQuery =
entityManager.createQuery(
"SELECT c FROM Country c WHERE country = ?",
Country.class);
typedQuery.setParameter(1, strCountry);
country = typedQuery.getSingleResult(); // Cause of deadlock in Thread-2 (for example)
} catch (NoResultException e) {
System.out.println("No data found for " + strCountry);
} catch (Exception e) {
e.printStackTrace();
}
return country;
}
Maybe private synchronized Country getCountry is provoking the deadlock? I don't think I should, since logDao has injected its own EntityManagerFactory
Can I use a connection pool?
Thanks in advance.
I am using hibernate in my Java EE application in combination with my Wildfly server to persist my Classes in a mysql Database.
So far this works fine but now I am writing unit tests and I am getting crazy about some error which I get.
I would like to test my DAO-Layer in my Unit-Tests but I get these errors:
Caused by: org.hibernate.engine.jndi.JndiException: Error parsing JNDI name [java:/MySqlDS]
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
my persistence.xml ist this:
<?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="primary">
<jta-data-source>java:/MySqlDS</jta-data-source>
<class>org.se.bac.data.Employee</class>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/empdb?useSSL=false"/>
<property name="hibernate.connection.username" value="student"/>
<property name="hibernate.connection.password" value="student"/>
<!--
SQL stdout logging
-->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>
So, Here I am using a jta-data-source> as you can see.
If I remove this line my tests are going fine! But I can not build my project with maven anymore.
Error:
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver]
Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver"}}
He can not find the datasource because I removed the line in my persistence.xml
How can I manage to get both run in my application. The tests and of course the maven build?
Here is my test: (Setup is already causing the error):
package org.se.bac.data.dao;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.se.bac.data.model.Employee;
public class EmployeeDAOTest
{
private static final JdbcTestHelper JDBC_HELPER = new JdbcTestHelper();
private final static JpaTestHelper JPA_HELPER = new JpaTestHelper();
private EntityManager em = JPA_HELPER.getEntityManager("primary");
private EmpDAO dao;
#BeforeClass
public static void init()
{
JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
JDBC_HELPER.executeSqlScript("sql/test/createEmployeeTable.sql");
}
#AfterClass
public static void destroy()
{
//JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
}
#Before
public void setUp()
{
JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
JDBC_HELPER.executeSqlScript("sql/test/createEmployeeTable.sql");
dao = new EmpDAOImpl();
dao.setEm(em);
JPA_HELPER.txBegin();
Employee emp2 = new Employee();
emp2.setFirstname("Max");
emp2.setLastname("Muster");
emp2.setHiredate("23-12-1991");
dao.insert(emp2);
}
And JPAHELPER Class:
package org.se.bac.data.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class JpaTestHelper
{
/*
* Property: persistenceUnitName
*/
private String persistenceUnitName;
public String getPersistenceUnitName()
{
return persistenceUnitName;
}
public void setPersistenceUnitName(String persistenceUnitName)
{
if(persistenceUnitName == null || persistenceUnitName.length() == 0)
throw new IllegalArgumentException("Illegal parameter persistenceUnitName = " + persistenceUnitName);
this.persistenceUnitName = persistenceUnitName;
}
/*
* Get an instance of the EntityManagerFactory.
*/
protected EntityManagerFactory getEnityManagerFactory()
{
if(persistenceUnitName == null)
throw new IllegalStateException("PersistenceUnitName must be set!");
return Persistence.createEntityManagerFactory(persistenceUnitName);
}
/*
* Manage an EntityManager.
*/
private EntityManager em;
public EntityManager getEntityManager()
{
if(em == null)
{
em = getEnityManagerFactory().createEntityManager();
}
return em;
}
public EntityManager getEntityManager(String persistenceUnitName)
{
setPersistenceUnitName(persistenceUnitName);
return getEntityManager();
}
public void closeEntityManager()
{
if(em != null)
em.close();
}
/*
* Handle Transactions
*/
protected void txBegin()
{
EntityTransaction tx = em.getTransaction();
tx.begin();
}
protected void txCommit()
{
EntityTransaction tx = em.getTransaction();
if(tx.getRollbackOnly())
{
tx.rollback();
}
else
{
tx.commit();
}
}
protected void txRollback()
{
EntityTransaction tx = em.getTransaction();
tx.rollback();
}
}
and my DAO:
package org.se.bac.data.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.se.bac.data.model.Employee;
class EmpDAOImpl // package private
implements EmpDAO
{
#PersistenceContext
private EntityManager em;
/*
* CRUD methods
*/
public Employee findById(int id)
{
System.out.println("empdaoimpl ID " + id);
return em.find(Employee.class, id);
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
}
Wildfly Datasource:
<datasources>
<datasource jta="true" jndi-name="java:/MySqlDS" pool-name="MySqlDS" enabled="true" use-ccm="false">
<connection-url>jdbc:mysql://localhost:3306/empdb?useSSL=false</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<driver>mysql-connector-java-5.1.44-bin.jar_com.mysql.jdbc.Driver_5_1</driver>
<security>
<user-name>student</user-name>
<password>student</password>
</security>
<validation>
<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
<background-validation>true</background-validation>
<exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
</validation>
</datasource>
</datasources>
He can not find the datasource because I removed the line in my persistence.xml
How can I manage to get both run in my application.
The problem is that the data source is managed by Wildfly which is not available on your test environment. So what you could do is define two separate persistence units (one for your production code and the other for the test) as follows:
<?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="primary">
<jta-data-source>java:/MySqlDS</jta-data-source>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<!-- SQL stdout logging -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
<class>org.se.bac.data.Employee</class>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/empdb?useSSL=false"/>
<property name="hibernate.connection.username" value="student"/>
<property name="hibernate.connection.password" value="student"/>
<!-- SQL stdout logging -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>
and then in your EmployeeDAOTest class modify the following line as:
private EntityManager em = JPA_HELPER.getEntityManager("testPU");
Note:
I removed the JDBC connection properties from the primary persistence unit because you don't need them as you already have the data source there on Wildfly.
I'm new to JPA and I'm having problems. I read that the problem maybe with the 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="GreekTravelPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>entities.Room</class>
<class>entities.Country</class>
<class>entities.User</class>
<class>entities.RoomType</class>
<class>entities.Role</class>
<class>entities.Photo</class>
<class>entities.Availability</class>
<class>entities.Message</class>
<class>entities.Location</class>
<class>entities.Booking</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/greektraveldb?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="psilos"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="psilos"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
My Exeption:
java.lang.IllegalArgumentException: Object: org.eclipse.persistence.internal.jpa.EntityManagerImpl#665ba601 is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.mergeCloneWithReferences(UnitOfWorkImpl.java:3510)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.mergeCloneWithReferences(RepeatableWriteUnitOfWork.java:384)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.mergeCloneWithReferences(UnitOfWorkImpl.java:3481)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.mergeInternal(EntityManagerImpl.java:542)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.merge(EntityManagerImpl.java:519)
The actual code is
#Override public void update(User user) {
EntityManager em = EntityManagerHelper.getEntityManager();
try {
EntityTransaction entityTrasacrion = em.getTransaction();
entityTrasacrion.begin();
em.merge(em);
entityTrasacrion.commit();
} catch (RuntimeException e) {
throw e;
} finally {
EntityManagerHelper.closeEntityManager();
}
}
You're merging the entity manager with the entity manager!!! Ooops!
em.merge(em);
Needs to be
em.merge(user);
Greeting for the day..
Please provide me support.
I am new in Jpa and calling procuder with #NamedStoredProcedureQuery but my code is giving Exception as #NamedStoredProcedureQuery NamedQuery of name: procuder not found
my code is :=
#NamedStoredProcedureQuery(name = "TEST1",procedureName = "TEST1",parameters = { #StoredProcedureParameter(name = "P_CODE", mode = ParameterMode.IN, type = String.class), #StoredProcedureParameter(name = "P_DATE", mode = ParameterMode.IN, type = String.class), #StoredProcedureParameter(name = "P_CURSOR", mode = ParameterMode.REF_CURSOR, type = void.class), })
public class AnotherWayOfCallingProcedure implements Serializable
{
private static final String PERSISTENCE_UNIT_NAME = "todos";
private static EntityManagerFactory factory;
public static void main(String arg[]) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
StoredProcedureQuery addBookNamedStoredProcedure = em.createNamedStoredProcedureQuery("TEST1");
addBookNamedStoredProcedure.setParameter("P_CODE", "5000");
addBookNamedStoredProcedure.setParameter("P_DATE", "5/3/2017");
// Stored procedure call
List createdBookId = addBookNamedStoredProcedure.getResultList();
em.close();
}
}
and persistence.xml is
<?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="todos" transaction-type="RESOURCE_LOCAL">
<class>com.app.IptAnchorageAreaMaster</class>
<class>com.app.AnotherWayOfCallingProcedure</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#192.168.6.147:1521:orcl" />
<property name="javax.persistence.jdbc.user" value="aaa_kkk" />
<property name="javax.persistence.jdbc.password" value="aaa" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="none" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
</persistence>