Container-managed EntityManger is null on Injection - jpa

I'm nearly new to JavaEE (JRE7/JDK1.7.0) and startet my first (maven based) Project on Eclipse (Luna).
Applicationserver is JBoss EAP 6.2.0.GA (AS 7.3.0.Final-redhat-14) which I updated to JSF2.2 by adding jsf-api-2.2.7.jar and jsf-impl-2.2.7.jar and registering in module.xml - which works perfect, by the way.
The problem/question is, why can't I get the EntityManager from the container (AS) with Injection, with following code in my Project:
#Stateless
public class SCatRep {
#PersistenceContext
EntityManager em;
private ...
*In persistence.xml there is only one persistenceunit defined. So no further arguments are necessary ... in my opinion?!
On the other hand, when I try to get the EntityManager from container with a lookup, the EntityManager is present and everything works fine. I used this code (for testing):
#Stateless
#PersistenceContext(unitName="scha", name="persistence/em")
public class SCatRep {
EntityManager em;
public SCatRep() {
try {
Context ic = new InitialContext();
em = (EntityManager) ic.lookup("java:comp/env/persistence/em");
} catch (NamingException e) {
e.printStackTrace();
}
}
I read a lot forums and tutorials - because this behaviour is discussed a lot - but can't get a solution or answer. Hope somebody can help me and point me to the right direction.
Thanks in advance.
EDIT:
I'm using EJB 3.1. And here is the persistence.xml:
<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="scha" transaction-type="JTA">
<jta-data-source>java:/scha_jndi</jta-data-source>
<properties>
<!-- SQL dialect -->
<property name="dialect" value="org.hibernate.dialect.MySQLDialect" />
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class" value="thread" />
<!-- Echo all executed SQL to stdout -->
<property name="show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>

Thanks for help.
I tried to access the EntityManager in constructor ... which is not possible, due to the initializationprocess.
Now I put the Initial loading (databaseaccess) in a #PostConstruct-annotated method and this works perfectly.

Related

how to set UserTransaction Eclipselink/Glassfish in multitenancy web-app

i spend a lot of time arround this question my project deals with WEB-APP/multitenancy
Eclipselink
Glassfish v4.1
Persistence Usage for Multiple Tenants : Persistence Unit per Tenant (according to eclipselink docs : Persistence Usage for Multiple Tenants
the persistence.xml si set as follow :
<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="myPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/mydata</jta-data-source>
<mapping-file>META-INF/eclipselink-orm.xml</mapping-file>
<class>...</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.multitenant.tenants-share-cache" value="false" />
<property name="eclipselink.exclude-eclipselink-orm" value="false"/>
<property name="objectdb.query-language" value="JPA" />
<property name="javax.persistence.lock.timeout" value="5000" />
</properties>
</persistence-unit>
</persistence>
inside a listener i put every new created EntityManagerFactory per tenant in a MAP and i call a static method to obtain an entity manager when needed
public static EntityManager createEntityManager(String tenant){
if(mapEMF.containsKey(tenant)){
return mapEMF.get(tenant).createEntityManager();
}else{
HashMap<String, String> properties = new HashMap<>();
properties.put(PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT, tenant);
properties.put(PersistenceUnitProperties.MULTITENANT_SHARED_EMF, "false");
properties.put(PersistenceUnitProperties.SESSION_NAME, tenant);
properties.put(PersistenceUnitProperties.CONNECTION_POOL_USER, "dbuser");
properties.put(PersistenceUnitProperties.CONNECTION_POOL_PASSWORD, "dbpass");
EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties);
mapEMF.put(tenant, emf);
return emf.createEntityManager();
}
}
my big question is how to obtain a transaction !
i have used but with no success
#Resource UserTransaction trasaction;
have created UserTransaction
transaction = (UserTransaction)new
InitialContext().lookup("java:comp/UserTransaction");
with em.joinTransaction();
the only method that works is em.getTransaction.begin()/em.getTransaction.commit();
but according the API/docs getTransaction is used in RESOURCE_LOCAL witch is not recommended for java ee web-app where we are called to use JTA as transaction type
Please HELP.

How do I get my project to use a container managed Enitymanager lifecycle rather an Application managed one?

I've been at this for a while - hoping to get some help. The first persistence.xml gives the output below it. The alternate persistence.xml crashes with: javax.persistence.PersistenceException: No Persistence provider for EntityManager named com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU Please let me know if there's anything I can ad to make this clearer.
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
#Stateless
public class NewClass {
#PersistenceContext(unitName ="com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU")
static EntityManager containerManagedEntityManager;
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(
"com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU");
EntityManager applicationManagedEntityManager = emf.createEntityManager();
System.out.println("Container managed entityManager: "+containerManagedEntityManager);
System.out.println( "Application managed entityManager: " +applicationManagedEntityManager);
}
}
The output:
[EL Info]: 2016-08-16 01:51:13.395--ServerSession(33510911)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
[EL Info]: connection: 2016-08-16 01:51:13.535--ServerSession(33510911)--file:/Users/me/NetBeansProjects/mavenproject1/target/classes/_com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU login successful
[EL Warning]: metamodel: 2016-08-16 01:51:13.552--The collection of metamodel types is empty. Model classes may not have been found during entity search for Java SE and some Java EE container managed persistence units. Please verify that your entity classes are referenced in persistence.xml using either <class> elements or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element
Container managed entityManager: null
Application managed entityManager: org.eclipse.persistence.internal.jpa.EntityManagerImpl#6f139fc9
My 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="com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/nutrition_DB"/>
<property name="javax.persistence.jdbc.user" value="app"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.password" value="pass"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
Alternate persistence.xml:
<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="persistenceUnit" transaction-type="JTA">
<jta-data-source>jdbc/dataSource</jta-data-source>
<class>test.domain.TestEntity</class>
</persistence-unit>
</persistence>
In order to have a container-managed entity manager, your should use the Java Transaction API (JTA) instead of RESOURCE_LOCAL. The different between them are :
JTA means the persistence is managed by the application server
RESOURCE_LOCAL means the persistence is managed by yourself.
You can see more difference for Persistence unit as RESOURCE_LOCAL or JTA?
So in your case, I suggest you to do the following :
Make sure you're in a Java EE environment, e.g. Tomcat, WildFly and not a Java SE.
Modify your PU com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU, set transaction-type="JTA"
Make sure that your JTA data source (DS) is configured in the server and activated
Describe this data source in your persistence XML in tag jta-data-source
Inject the EntityManager into you java class using PersistenceContext as you've done. Since the persistence is managed by the application server, do not use entity manager factory anymore except you know exactly what you're doing.
However, it seems that you're under the Java SE environment. In the case, there isn't any Java EE container (application server). And therefore, you cannot benefit the JTA configuration :( You must use RESOURCE_LOCAL mode and manage everything yourself.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named avaliacaoneomind

I have a EJB project example that uses #PersistenceContext to conect to my database.
This works fine, but since my new project isn't a EJB, I have to think of another way to to this.
So I came up with something like this:
EntityManagerFactory entityFactory = Persistence.createEntityManagerFactory("avaliacaoneomind");
EntityManager em = entityFactory.createEntityManager();
But when I do this, I get this error:
javax.persistence.PersistenceException: No Persistence provider for EntityManager named avaliacaoneomind
I know my persistence.xml is correct AND in the right place because when I use #PersistenceContext(name="avaliacaoneomind") as a test, my tables are created automaticaly in my DB. If I remove the #PersistenceContext away from my code, the tables arent created.
How do I fix this error? I tried all links possible to find and none of them seems to fix my problem.
Bellow is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence>
<!--Nome do contexto que configura o Provedor de PersistĂȘncia -->
<persistence-unit name="avaliacaoneomind">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/avaliacaoneomind</jta-data-source>
<properties>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="both" />
</properties>
</persistence-unit>
</persistence>
You can achieve the entityManager through JNDI lookup
Context initCtx = new InitialContext();
javax.persistence.EntityManager entityManager =
(javax.persistence.EntityManager)initCtx.lookup(
"java:comp/env/avaliacaoneomind"
);

Openshift application and ejb "failed deployments ./ROOT.war

I'm developing a first application on openshift. Its a jsf application with database connectitivity.
First i tryed onli some jsf xhtml page without jpa and all works.
When i insert a bean to acces to the database i have the message from the server "failed deployments ./ROOT.waer. Precisely when I insert this code something goes wrong :
A class for view intents
#ManagedBean(name="utnavctrl" ,eager=true)
#SessionScoped
public class Utnavctrl {
boolean newrecord=false;
#EJB
private Usersdao usersdao;
public Utnavctrl(){
A bean class for db connection
#Stateless
#LocalBean
public class Usersdao {
#PersistenceContext(unitName = "primary")
private EntityManager em;
public Usersdao() {
// TODO Auto-generated constructor stub
}
public List<User> getAllUsers() {
return em.createNamedQuery("User.findAll", User.class)
.getResultList();
}
I can't understand why after adding these two class (without modifing the view side xhtml ecc) the program doesn't work anymore.
The persince.xml is
<?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">
<!-- If you are running in a production environment, add a managed
data source, this example data source is just for development and testing! -->
<!-- The datasource is deployed as WEB-INF/kitchensink-quickstart-ds.xml, you
can find it in the source at src/main/webapp/WEB-INF/kitchensink-quickstart-ds.xml -->
<jta-data-source>java:jboss/datasources/MySQLDS</jta-data-source>
<class>com.antoiovi.gestcars.model.Automobili</class>
<class>com.antoiovi.gestcars.model.Group</class>
<class>com.antoiovi.gestcars.model.Prenotazioniauto</class>
<class>com.antoiovi.gestcars.model.Proglav</class>
<class>com.antoiovi.gestcars.model.Role</class>
<class>com.antoiovi.gestcars.model.User</class>
<class>com.antoiovi.gestcars.model.UserData</class>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
Thhe bean.xml is
<?xml version="1.0" encoding="UTF-8"?>
<!-- This file can be an empty text file (0 bytes) -->
<!-- We're declaring the schema to save you time if you do have to configure
this in the future -->
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</bean
Can anybody help me?
Remove eager=true because this creates problems with OpenShift...I do not know why but I have seen.

Configuring EJB on JBoss AS 7 using JTA datasources: every statement is commited

everybody!
I've been trying to find the answer for some time but I didn't manage.
I try to configure my application and make it work under JBoss Application Server 7.1.1, using Enterprise Java Beans. My application is Web application, it uses servlets and injects other classes as EJBs. The problem is that every statement gets commited, so that means no transaction management is supported.
In my test example I have an entity with a collection of children (mapped with a relationship OneToMany with a property CascadeType.ALL). If a record in a collection has some problems (e.g. non-existing foreign key), it can't be inserted into table and throws exception. However, the parent entity gets inserted, so I assume the inserts are done in different separate transactions. This is strictly undesired behavior and I try to resolve it.
Technical parameters:
DBMS: Oracle EE 11g
AS: JBoss AS 7.1.1
my 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/">
<persistence-unit name="OracleEntityManager">
<jta-data-source>java:jboss/CmaDevDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9iDialect" />
<property name="hibernate.hbm2ddl.auto" value="none" />
<property name="hibernate.jdbc.batch_size" value="20" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.use_sql_comments" value="true" />
</properties>
</persistence-unit>
</persistence>
my EJB:
#Stateless(name="EntityWriter")
#TransactionManagement(TransactionManagementType.CONTAINER)
public class EntityWriter {
#Resource
private SessionContext context;
/*#Resource
UserTransaction ut;*/
#PersistenceContext(unitName = "OracleEntityManager",type=PersistenceContextType.EXTENDED)
EntityManager em;
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public EntityMarker insertEntity(EntityMarker entity)throws Exception
{
try
{
entity = em.merge(entity);
em.flush();
return entity;
}
catch (Exception e)
{
context.setRollbackOnly();
e.printStackTrace();
return null;
}
}
}
Actually I tried both EJB approaches: Container Management Transaction and Bean Management Transaction and neither works as I expect.
When I inject the bean into servlets I do it like this:
#EJB(name = "EntityWriter")
private EntityWriter entityWriter;
Now I think the bean is fine, probably something is missing in persistence.xml.
Would be grateful to any ideas. Thanks in advance!
Everything works correct after I edited Datasource configuration via JBoss Administration console and set a checkbox "Use JTA". It was unchecked by default.
You're right, Chris. Thanks!