EJB Maven module using JPA - maven

I have simple maven EJB module using JPA. This is my persistance.xml file
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Persistence">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>GroupTypes.xml</mapping-file>
<properties>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#127.0.0.1:1521:E"/>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.username" value="username"/>
<property name="hibernate.connection.password" value="password"/>
</properties>
</persistence-unit>
</persistence>
I am using EJB Stateless Bean and I am trying to get all attributes from GroupTypes table. This is my bean implementation:
public class TestBean
{
private GroupTypes GroupTypes;
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
#WebMethod (operationName = "justTesting")
public boolean justTesting(#WebParam (name = "param") String value)
{
try
{
entityManagerFactory = Persistence.createEntityManagerFactory("Persistance");
entityManager = entityManagerFactory.createEntityManager();
Query query = entityManager.createQuery("Select name from GroupTypes");
List<AmmEdGroupTypes> result = query.getResultList();
return true;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}
}
When I try to invoke this method I get exeption: javax.persistence.PersistenceException: No Persistence provider for EntityManager named Persistance.
My persistance.xml file is placed in folder resources/META-INF/persistance.xml, and if I am not using bean this solution works. Does anydbody have some idea why this is happening only in case when I am using bean?
I am using Intellij 12.1.1, Oracle 11g, Glassfish 3.1 server and JAVA 1.6.

I solved this problem in the following way:
Installed hibernate add-on on glassfish (using glassfish update tool)
On glassfish added jdb connection pool _AmmPool with properties: className, username,password,databaseName and url
On glassfish added jdbc resource jdbc/__amm binding with connection pool _AmmPool
Changed persistence.xml file
Changed pom.xml file
Copied the following libraries into glassfish domains/domain1/lib folder:
antlr-2.7.7
commons-collections-3.2.1,
dom4j-1.6.1,
ejb3-persistence-1.0.2.GA,
hibernate3-maven-plugin-3.0,
hibernate-commons-annotations-4.0.2.Final,
hibernate-core-4.2.2.Final,
hibernate-entitymanager-4.2.2.Final,
javassist-3.15.0-GA,
jta-1.1,
log4j-1.2.17,
oracle-jdbc-11.1.0.6.0-Production+,
slf4j-api-1.6.1
slf4j-log4j12-1.7.5
A also copied these libraries into glassfish/lib floder.
This is my new persistance.xml file: http://pastebin.com/xbEU9Tr0
And this is my pom.xml file: http://pastebin.com/uEjhW36

Related

JPA entityMangerFactory not found through Persistence.createEntityManagerFactory("XYZ")

Any help will be greatly appreciated.
We are working on a web application. Which uses a JAR file (a java maven project) and has been added as a maven dependency in the web application.
Combination of this JAR file and web application itself creating problem.
Both web application and JAR are using Hibernate JPA to interact with database. But both are using 2 different ways for creating/initializing entityManagerFactory.
Web Application uses Spring xml based configuration to initialize entityManagerFactory.
CODE:
persistence.xml code:
<persistence-unit name="org.jbpm.persistence.jpa.local"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>META-INF/JBPMorm-JPA2.xml</mapping-file>
<class>org.drools.persistence.info.SessionInfo</class>
<class>org.jbpm.persistence.processinstance.ProcessInstanceInfo</class>
<class>org.drools.persistence.info.WorkItemInfo</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
<property name="hibernate.max_fetch_depth" value="3" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
Spring configuration:
<context:component-scan base-package="com.company.rd.core" />
<context:component-scan base-package="com.company.rd.services" />
<jee:jndi-lookup id="testDataSource" jndi-name="java:comp/env/jdbc/SybaseDB" />
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="testDataSource"/>
<property name="defaultTimeout" value="120"></property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="org.jbpm.persistence.jpa.local" />
<property name="dataSource" ref="testDataSource" />
<property name="jpaDialect" ref="jpaDialect" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="jpaDialect" ref = "jpaDialect"></property>
<property name="defaultTimeout" value="120"></property>
</bean>
<jee:jndi-lookup id="logDataSource" jndi-name="java:comp/env/jdbc/DRMLOG" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>
And Here is the code to initializing entitymanagerFactory in JAR file.
persistence.xml
<persistence-unit name="codeAuthorization" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>java:/comp/env/jdbc/SybaseDB</non-jta-data-source>
<class>com.company.auth.entity.AuthorizationCode</class>
<class>com.company.auth.entity.UserInvalidAttempt</class>
<class>com.company.auth.entity.AuthorizationProperty</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
And a java file which is injected into Base DAO through spring.
#Service
public class AuthorizationEntityMangerService {
#PersistenceUnit(name = "codeAuthorization")
private EntityManagerFactory entityManagerFactory;
public AuthorizationEntityMangerService() {
entityManagerFactory = Persistence
.createEntityManagerFactory("org.jbpm.persistence.jpa.local");
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
public EntityManager getEntityManager() {
return this.entityManagerFactory.createEntityManager();
}
public void closeEntityManager(EntityManager entityManager) {
if (entityManager != null && entityManager.isOpen()) {
entityManager.close();
}
}
public EntityTransaction getTransaction(EntityManager entityManager) {
return entityManager.getTransaction();
}
public void rollBackTransaction(EntityTransaction transaction) {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
}
public void commitTransaction(EntityTransaction transaction) {
if (transaction != null && transaction.isActive()) {
transaction.commit();
}
}
}
Calling code from Base DAO.
public Object getSingleResult(final String queryString, final String key,
final NamedQueryParameter namedQueryParameter) {
EntityTransaction transaction = null;
EntityManager entityManager = null;
try {
entityManager = this.entityMangerService.getEntityManager();
transaction = entityMangerService.getTransaction(entityManager);
transaction.begin();
final Query query = entityManager.createQuery(queryString);
setQueryParameter(query, namedQueryParameter);
final Object result = query.getSingleResult();
entityMangerService.commitTransaction(transaction);
return result;
} catch (final NoResultException e) {
entityMangerService.rollBackTransaction(transaction);
logger.error("Error" : " + e.getMessage());
return null;
} finally {
entityMangerService.closeEntityManager(entityManager);
}
}
Now Here is the problem when ever line entityManager.createQuery(queryString); execute it throws the exception.
2015-06-05 17:39:46,363 WARN DefaultExceptionHandler:94 - Unhandled exception caught by the Stripes default
exception handler.
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: AuthorizationProperty is
not mapped [SELECT pe.value FROM AuthorizationProperty pe WHERE pe.name=:propertyName AND pe.deleted=0]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1364)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke
(ExtendedEntityManagerCreator.java:334)
at com.sun.proxy.$Proxy53.createQuery(Unknown Source)
at com.company.authentication.dao.AuthorizationBaseDAO.getSingleResult(AuthorizationBaseDAO.java:40)
at com.company.authentication.dao.PropertyDAOImlp.getPropertyValue(PropertyDAOImlp.java:22)
at com.company.authentication.services.AuthorizationPropertyService.getPropertyValueByName
(AuthorizationPropertyService.java:19)
at com.company.rd.servlet.JspAuthorizationRestFilter.hasAuthorizationCode
(JspAuthorizationRestFilter.java:105)
at com.company.rd.servlet.AbstractAuthorizationRestFilter.isRequestAuthenticated
(AbstractAuthorizationRestFilter.java:120)
at com.company.rd.servlet.JspAuthorizationRestFilter.doFilter(JspAuthorizationRestFilter.java:84)
I have debugged the code and found entityManagerFactory for persistenceUnit "codeAuthorization" is not initialized. Only "org.jbpm.persistence.jpa.local" is available (verified through eclipse debugger) inside this method.
Note: This JAR is working fine in some other application where web application and JAR using same way to initialize entityMangerFactory [through Persistence.createEntityManagerFactory("")].
Please let me know How can I get "codeAuthorization" entiryManagerFactory
You are using Spring then use Spring, currently you are doing a lot of work to work around Spring and dependency injection and managed transaction. Don't use Persistence.createEntityManagerFactory(""). Just inject the EntityManager where you need it using an EntityManager field annotated with #PersistenceContext and specify the name of the one you want.
Also don't manage the transactions, entity manager yourself, spring does that for you. For this use the right PlatformTransactionManager the JpaTransactionManager and not the DatasourceTransactionManager as that won't work in a JPA environment. (At least not to manage your JPA transactions).
Doing this will really simplify your code and your life.
So basically ditch the service that is doing those nasty things and simple do things like this in your dao.
#Repository
public class YourDao {
#PersistenceContext(name="codeAuthorization")
private EntityManager em;
#Transactional
public Object getSingleResult(final String queryString, final String key,
final NamedQueryParameter namedQueryParameter) {
final Query query = em.createQuery(queryString);
setQueryParameter(query, namedQueryParameter);
return query.getSingleResult();
}
}
In your configuration replace the DatasourceTransactionManager with the JpaTransactionManager and add <tx:annotation-driven />. Then clean your code.
Note: The JpaTransactionManager is perfectly capable of managing plain JDBC transactions if you still need those, ideally you would have a single transaction manager.

Spring equivalent of #Stateless EJB with multiple #PersistenceContext

I've been banging my head on the wall for the past couple of days trying to get this to work but I've not been able to.
I wrote a JPA EntityManagerProvider recently using EJB:
EntityManagerProviderBean.java
#Stateless
public class EntityManagerProviderBean {
#PersistenceContext(unitName="PU1")
private EntityManager entityManager1;
#PersistenceContext(unitName="PU2")
private EntityManager entityManager2;
public EntityManager getEntityManager() {
return (...) ? entityManager1: entityManager2;
}
}
And then of course I can inject the EJB wherever needed like this:
UserFacade.java
#Stateless
public class UserFacade {
#EJB
private EntityManagerProviderBean emProvider;
private EntityManager em = emProvider.getEntityManager();
...
}
Now I'm trying to do something similar using Spring, using annotations, and without doing anything in XML. I can't seem to figure out a way to inject the EntityManager. Anything that I do leads to a NullPointerException. For example, I tried to inject the EntityManager manually without relying on my EntityManagerProviderBean, like this:
UserFacadeSpring.java
public class UserFacadeSpring {
#PersistenceContext(unitName="PU1")
private EntityManager em;
...
}
But this gives me a NullPointerException. So the EntityManager is not being injected at all and I'm not sure what's wrong.
So two questions basically:
How can I inject the EntityManager using Spring?
How can I use my existing EntityManagerProviderBean EJB in Spring? What modifications do I need to make?
Any help in this matter will be greatly appreciated. As you can tell I'm a complete noob to Spring. I tried to read the guide but everything's flying over my head at the moment. I actually did try to do something half-baked but it didn't work either (I either get NullPointerException or BeanNotFoundException, I must have used every combination of #Component, #Bean, #Autowired annotations I think!):
EntityManagerProviderSpring.java
#Component
public class EntityManagerProviderSpring {
#PersistenceContext(unitName="PU1")
private EntityManager entityManager1;
#PersistenceContext(unitName="PU2")
private EntityManager entityManager2;
#Bean
public EntityManager getEntityManager() {
return (...) ? entityManager1: entityManager2;
}
}
Main.java
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(EntityManagerProviderSpring.class);
EntityManagerProviderSpring emProvider = context.getBean(EntityManagerProviderSpring.class);
EntityManager em = emProvider.getEntityManager();
...
}
Thanks!
EDIT: I'm using Hibernate with JPA and the following is my persistence.xml file:
<?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="PU1" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>...</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/db1?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="pu1_username"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="pu1_pwd"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
</properties>
</persistence-unit>
<persistence-unit name="PU2" transaction-type="RESOURCE_LOCAL">
...
</persistence-unit>
</persistence>
To have the exact same functionality on dependency injection level, it is impossible to map stateless ejb bean to a spring bean.
EJB #Singleton -> Spring #Component (or #Service or #Controller or #Repository)
EJB #Stateful -> Spring #Component#Scope("prototype") (or #Service#Scope("prototype") or #Controller#Scope("prototype") or #Repository#Scope("prototype"))
EJB #Stateless -> DOES NOT EXIST IN SPRING.
Stateless beans are very handy for this multiple persistence contexts... However, since Spring doesn't offer stateless bean. You have to use custom Spring setup to apply multiple persistence context. It won't work with only persistence.xml like EJB, unfortunately :(.
So to answer your questions:
Read Spring doc... Plenty of examples everywhere. Shortly, In Spring 4 Java Config you can use #EnableTransactionManagement, a transaction manager and an entity manager factory per persistence context.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/ejb.html. This is how you do it. Not a nice way since using jndi, but it is a solution...

Injection of autowired dependencies failed while using #Transactional

I testing my DAO, but it didn't work. The following error occurs:
Tests in error:
testAccountOperations(com.tsekhan.rssreader.dao.HibernateControllerTest): Error creating bean with name 'com.tsekhan.rssreader.dao.HibernateControllerTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.tsekhan.rssreader.dao.HibernateController com.tsekhan.rssreader.dao.HibernateControllerTest.hibernateController; nested exception is java.lang.IllegalArgumentException: Can not set com.tsekhan.rssreader.dao.HibernateController field com.tsekhan.rssreader.dao.HibernateControllerTest.hibernateController to $Proxy25
My DAO:
#Service
#Scope("singleton")
public class HibernateController extends HibernateDaoSupport {
#Autowired
public SessionFactory sessionFactory;
#Transactional
public void addAcount(Account account) {
sessionFactory.getCurrentSession().saveOrUpdate(account);
}
}
My test for this DAO:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/applicationContext.xml")
public class HibernateControllerTest {
#Autowired
HibernateController hibernateController;
private Set<Channel> getTestChannelList(String channelLink) {
Channel testChannel = new Channel();
testChannel.setSourceLink(channelLink);
Set<Channel> testChannelList = new HashSet<Channel>();
testChannelList.add(testChannel);
return testChannelList;
}
private Account getTestAccount(String accountLogin, String channelLink) {
Account testAccount = new Account();
testAccount.setAccountLogin(accountLogin);
testAccount.setChannelList(getTestChannelList(channelLink));
return testAccount;
}
#Test
public void testAccountOperations() {
hibernateController
.addAcount(getTestAccount("test_login", "test_link"));
}
}
My applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd"
default-autowire="byName">
<!-- Enabling spring-transaction annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Enabling annotation-driven configurating -->
<context:annotation-config />
<!-- Creation of transaction manager -->
<bean id="transactionManager" scope="singleton"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="sessionFactory" scope="singleton"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="configLocation" value="classpath:/hibernate.cfg.xml"/>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
</bean>
<!--
A Spring interceptor that takes care of Hibernate session lifecycle.
-->
<bean id="hibernateInterceptor"
class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean name="employeeDAO" scope="prototype"
class="com.tsekhan.rssreader.dao.HibernateController" />
<!-- Searching for hibernate POJO files in package com.tsekhan.rssreader.web -->
<context:component-scan base-package="com.tsekhan.rssreader.web" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
</beans>
I note, that if you comment #Transactional in DAO, bean is created correctly. What happens?
First of all its realy bad to give name ending in Controller to a DAO its very confusing, Controller and DAO have all together different purpose.
When you add #Transactional to a service or dao class, for spring to make it work in a transaction needs to create a proxy of that class, its a kind of wrapper where in before the execution of proxied class(class in consideration which is proxied) method spring starts the transaction and after the execution in case no exceptions completes the transaction, this can be done in spring via AOP and Annotations. To describe in code.
public class OriginalDaoImpl implements OriginalDao extends DaoSupport {
public void save(Object o){
manager.save(o);
}
}
public class ProxyDaoImpl implements OriginalDao {
private OriginalDao originalDaoImpl; //instance of OriginalDaoImpl
public void save(Object o){
try{
transaction.start();
originalDaoImpl.save(o);
transaction.commit();
}catch(Exception e){
transaction.rollback();
}finally{
//clean up code
}
}
}
As you see this is not an exact implementation but a foundation code, how transaction magically works for you. The key point is there interface OriginalDao which makes this injection easy as OriginalDaoImpl and ProxyDaoImpl both implement same interface. Hence they can be swapped i.e. proxy taking place of original. This dynamic proxy can be created in java by Java dynamic proxy. Now, the question what if your class is not implementing an interface, it gets harder for the replacement to happen.
One of the libraries CGLIB as far as I know, helps in such a scenario, whereby it generates a dynamic subclass for the class in consideration and in overriden method performs the magic as described above, by calling super.save(o) to delegate to original code.
Now to the problem of injection.
Create interface and make your dao implement that and spring will default to JDK proxy as it is behaving now.
Add proxy-target-class="true" attribute to <tx:annotation-driven transaction-manager="transactionManager"/>
As far as exception is concerned it is throwing as it is expecting injected bean to be of type 'HibernateController' but its not.
For you reference you can refer links below.
10.5.6 Using #Transactional
Spring AOP Doc
Hope this helps !!!!!.
If your are using Spring MVC make sure to scan specific controller classes alone in servlet context file. Otherwise it will scan 2 times and transaction is not available on the application context.

Entitymanager is null when inject by glassfish

*when i deploy project in glassfish entitymanager is null.if i use another thing instead of RPC like servlet project work probably *
session bean is:
#Stateless
public class logic implements logicLocal {
#PersistenceContext(unitName="T2PU")
private EntityManager em;
#Override
public void addToDB(Test t){
em.persist(t);
}
}
and GWT RPC is :
public class MainRPCImpl extends RemoteServiceServlet implements MainRPC {
#EJB
logicLocal logic;
#Override
public String addToDB(Test t) {
String m="fail";
try {
logic.addToDB(t);
m="done successfuly";
} catch (Exception e) {
return m;
}
return m;
}
}
persistence unit is :
<persistence-unit name="T2PU" transaction-type="JTA">
<jta-data-source>acm</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
and glassfish-resources
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysql_acm_rootPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="acm"/>
<property name="User" value="root"/>
<property name="Password" value="1234"/>
<property name="URL" value="jdbc:mysql://localhost:3306/acm"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="acm" object-type="user" pool-name="mysql_acm_rootPool"/>
</resources>
specially thanks in advance.
Maybe there are different reasons, but don't you need to use the jdbc context prefix for your JNDI name in persistence.xml? Something like this:
<jta-data-source>jdbc/acm</jta-data-source>
From the Glassfish administration guide:
A JDBC resource is created by specifying the connection pool with
which the resource will be associated . Use a unique Java Naming and
Directory Interface (JNDI) name to identify the resource. ... Because
all JNDI names are in the java:comp/env subcontext, when specifying
the JNDI name of a JDBC resource in the Administration Console, use
only the jdbc/name format.

In Spring MVC 3.0.5 controller JPA entity not getting persisted to the database

In the code below, persist() returns w/o an exception but the entity is not stored in the database.
#RequestMapping(method = RequestMethod.POST)
public String form() {
EntityManager em = this.emf.createEntityManager();
TaxRates t = new TaxRates();
t.setCountry("US");
// set more properties
em.persist(t);
em.close();
...
}
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="TT-SpringMVCPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
...
<class>com.sajee.db.TaxRates</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:jtds:sqlserver://localhost:1234/mydb"/>
<property name="javax.persistence.jdbc.password" value="Password1"/>
<property name="javax.persistence.jdbc.driver" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
</properties>
</persistence-unit>
</persistence>
I don't need any transaction support or any fancy enterprise feature support. I simply want to create an entity and save it to the database.
Where am I going wrong?
persist() doesn't write your object to the database immediately. Instead, it marks your object as persistent, so that it will be written to the database before transaction commit (or before executing a query, or during explicit flush() operation).
So, even if you don't need transactional behaviour you still have to manage transactions. You can do it manually as follows:
#RequestMapping(method = RequestMethod.POST)
public String form() {
EntityManager em = this.emf.createEntityManager();
TaxRates t = new TaxRates();
t.setCountry("US");
// set more properties
em.getTransaction().begin();
em.persist(t);
em.getTransaction().commit();
em.close();
...
}
But Spring's declarative transaction support is a more convenient way to do it.

Resources