EntityManager in SSB null - java

I am trying to update a small alpha version of a enterprise application originally written in Java6. Now I want to use:
Java 7
JSF latest
Maven
EJB 3.2 with Glassfish
So far I can deploy my EAR file on Glassfish without problems. My webapp can be loaded, the first JSF pages navigate fine. And my JSF backing bean seems to also load my Stateless session beans fine. Debugging showed me, I can get from one SSB to another coming from my backing bean. The last and final step that I am missing is my entity manager and persistence.
My class is annoated with #Stateless and i am using:
#PersistenceContext(unitName = "myProjectPU")
protected EntityManager entityManager;
But the entity manager is null :(
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="myProjectPU" transaction-type="JTA">
<jta-data-source>jdbc/myProject</jta-data-source>
<properties>
<property name="javax.persistence.schema-generation.create-database-schemas" value="true" />
</properties>
</persistence-unit>
</persistence>
Any ideas? Does the persistence.xml have to be inside the ear maven module? Right now its in the ejb maven module, where my classes which use the entity manager reside.

Well finally I found the problem. Scrolling up in the glassfish logs showed that the nullpointer exception followed up an earlier exception that stated "No database selected". The problem was not in the code, but in the Glassfish JDBC Connection that I made. My ping worked fine and i thought the connection was ok. But you dont only have to add the mysql port and username and password. You also MUST change the default URL and add (additional properties in connection pool) the following value:
jdbc:mysql://localhost:3306/yourdatabase
before it was defaulted to:
jdbc:mysql://:3306/
Take also care that there are two parameters, Url and URL! After that not only the ping succeeded, but also the database connection with entity manager worked fine. :(

Related

EntityManager is always null on REST project (netbeans) running on weblogic 12c

I've been working on a REST project on Netbeans 8.2 (compiled using Java 1.7). I'm deploying my web project on a Weblogic Server 12.1.2 and using JPA (w/ Eclipselink) as the persistence engine referencing a JTA datasource that is configured on server.
The problem I have is common from what I investigated in google; however, I was not able to find any solution on the Web that helps me with the issue.
Basically, this is how my persistence.xml file is defined:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="gchPermissionPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc.vz.customer.ds</jta-data-source>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-server" value="WebLogic"/>
<property name="javax.persistence.query.timeout" value="660000"/>
<property name="eclipselink.logging.level" value="ALL"/>
<property name="eclipselink.persistence-context.flush-mode" value="COMMIT"/>
<property name="eclipselink.cache.shared.default" value="false"/>
</properties>
</persistence-unit>
</persistence>
This is how I use the EntityManager on a class:
#PersistenceContext(unitName = "gchPermissionPU")
protected EntityManager entityManager;
I get the NullPointerException whenever this line is called (the only one in which I reference entityManager by now):
Query permissionsQuery = entityManager.createNativeQuery(nativeSqlQuery.toString());
I believe the NullPointer comes up because the entityManager variable is null.
Here's the basic data source configuration on my weblogic:
I wonder if I need some kind of additional configuration in the weblogic side or any missing piece of code.
Thanks in advance for your time and help. Any clue/feedback is appreciated.
I managed to solve my problem by manually creating EntityManagerFactory and EntityManager, from this answer:
PersistenceContext EntityManager injection NullPointerException
Seems like without EJB references, you need to force the creation of your persistence components. So my team came up with the following solution:
//1. Define the components required for persistence:
#PersistenceUnit(unitName = "gchPermissionPU")
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
//2. Just a method that will create entity manager factory if it is "null"
public final EntityManager getEntityManager() {
if (entityManagerFactory == null) {
entityManagerFactory = Persistence.createEntityManagerFactory("gchPermissionPU");
}
if (entityManager == null) {
entityManager = entityManagerFactory.createEntityManager();
}
return entityManager;
}
However, I wonder to know if this is the best solution for a Web application that will be used by > 1000 users. I can't believe that a Web application should rely on EJB for injection (maybe because it is Weblogic) but I remember I implemented a similar application on Tomcat some time ago and didn't need to make this "workaround".
If somebody has additional comments or feedback, please let me know.
Thanks.

StandAlone CDI + JTA Without JNDI

I am using CDI + DeltaSpike + Camel in a standalone app.
Here is my current setup :
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="primary" transaction-type="RESOURCE_LOCAL">
<shared-cache-mode>DISABLE_SELECTIVE</shared-cache-mode>
</persistence-unit>
Custom properties on EntityManagerFactoryProducer:
properties.put("hibernate.connection.provider_class", "org.example.HikariConnectionProvider");
I'm using DeltaSpike JPA Transaction with (https://deltaspike.apache.org/documentation/jpa.html):
org.apache.deltaspike.jpa.api.transaction.TransactionScoped;
org.apache.deltaspike.jpa.api.transaction.Transactional;
I would like to use Infinispan to sync my app caches.
According to Infinispan doc:
"It is highly recommended that Hibernate is configured with JTA transactions"
How can I use JTA transactions ?
I tried to change "RESOURCE_LOCAL" to "JTA" but I don't understand what am I supposed to configure for :
hibernate.transaction.factory_class
hibernate.transaction.jta.platform
I am not using JNDI, and I am not in an application server.
Also, I would like to use #javax.transaction.Transactional instead of DeltaSpike.
Essentially, you are asking how to use most Java EE features without using a Java EE container.
Of course, there are JTA implementations like Atomikos you can embed in a "standalone" application.
On the other hand, it might be a lot easier to start with a full-blown Java EE environment and then ignore or exclude anything you don't need.
App servers are rather lightweight these days, and if a self-contained executable is a must-have for you, then have a look at WildFly Swarm or Payara Micro.

UTF - 8 with JPA and Glassfish 4.0

I am having difficulties with UTF-8 characters. This is a simple JSF project. I use JSF 2.2 and Glassfish 4.0
I have a method where I go:
em.persist(user);
When I debug
user.getName()
in this point, I can see the utf-8 characters in my IDE. Also I keep the string in a session - bean and I can see them on the browser fine as well.
Only when they are persisted to DB, they are persisted as: ?????
I can also edit the DB myself and save utf-8 characters. What I mean is, my SQL configuration is good for UTF-8.
The problem is somewhere in JPA.
This is what I have tried: ( all together: )
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Persistence" transaction-type="JTA">
<jta-data-source>fus</jta-data-source>
<class>com.tugay.fup.core.model.User</class>
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/fus?useUnicode=yes&characterEncoding=UTF-8"/>
</properties>
</persistence-unit>
</persistence>
This is glassfish-web.xml:
<glassfish-web-app>
<parameter-encoding default-charset="UTF-8"/>
</glassfish-web-app>
And I am using EntityManager managed by container (transaction type = JTA)
So in JDBC connection pools in Glassfish I have:
jdbc:mysql://localhost:3306/fus?useUnicode=true&connectionCollation=utf8_general_ci&characterSetResults=utf8
for: property: URL...
However none of these help.
Still characters not persisted correctly.
When using Glassfish, you can set these properties as additional to your JDBC Connection Pools. Locate and view your database connection in Web Administration (Resources->JDBC Connection Pools->your.connection). In additional properties tab add (if there are not present yet) mentioned properties and restart your server:
//name, value
characterEncoding, UTF-8
characterSetResults, UTF-8
useUnicode, true
The result will be the same if parameters are added to URL, but this is more maintainable solution in my opinion.
This solved it:
jdbc:mysql://localhost:3306/fus?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8
so this was wrong:
jdbc:mysql://localhost:3306/fus?useUnicode=true&connectionCollation=utf8_general_ci&characterSetResults=utf8

How to use Spring to manage connection to multiple databases

I have read other topics but didn't find a good and clear answer
What I'm trying to is to develop a web app which is able to:
1) Log/track user events in a seperate UI database which we connect via hibernate with the same database schema (maybe save connectionString to the different oracle databases)
2) At runtime when you log in you can choose an environment to connect to one of the three different oracle databases that have the same schema (but not the same data)
3) provide the correct DataSource with username and password (where to get this sensitive data? I would not keep this stored somewhere in the application)
I'm fairly new to the Spring framework. I found this link which could be a first lead.
Any suggestions?
Also using Spring 3.1 or 3.2, JDBC to query to my oracle database and hibernate mapping to my UI database. This sounds quite confusing so I have a picture:
infrastructure
Just create different DAOs each with a separate persistence-unit attached to them.
In your persistence.xml you can have multiple persistence-unit's each connecting to a different database.
Example:
public class Dao1{
#PersistenceContext(unitName="Database1")
protected EntityManager entityManager;
public class Dao2{
#PersistenceContext(unitName="Database2")
protected EntityManager entityManager;
<?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="Database1">
<exclude-unlisted-classes />
<properties>
</properties>
</persistence-unit>
<persistence-unit name="Database2">
<exclude-unlisted-classes />
<properties>
</properties>
</persistence-unit>
</persistence>
The link you have mentioned in your post says following:
1) create different data sources pointing to different schema.
2) extends AbstractRoutingDataSource and create your own data source, override determineCurrentLookupKey method which will provide value of key. in your case it will return whatever user choose from UI. also in the bean definition of your custom data source pass all the data source as map with key as option available at UI.
3) Now assign this data source into your session factory bean.

EntityManager injection results in NullPointerException

I'm writing my first Java EE (EJB + Servlets etc.) application (please note: I'm using Eclipse).
I'm stuck with a problem with EntityManager injection not working, and having some difficulties finding why due to my Java EE (and Java in general) noobness.
Here is my persistence.xml file - I think this is mostly correct, since I can launch the HSQL database manager from the JMX console and my PUBLIC.USER table shows up correctly.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="MyPu">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
Here's my servlet code:
[...]
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
String id = request.getParameter("username");
String password = request.getParameter("password");
UserManagerBean um = new UserManagerBean();
um.register(username, password);
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
}
And here's my UserManagerBean Class:
//bunch of imports
import myPackage.UserManager;
public #Stateful class UserManagerBean implements UserManager {
#PersistenceContext(unitName="MyPu")
private EntityManager persistManager;
public void register(String username, String password) {
User user = new User(userame, password);
persistManager.persist(user);
persistManager.flush();
}
}
The persistManager.persist(user) line throws a NullPointerException.
From my own searching I understood that this is happening because, since I'm calling new() on UserManagerBean the injection from the #PersistenceContext annotation never takes place and persistManager never gets bound.
If so, it is evident that I'm missing something about the proper usage of EJBs.
What is the right way to instantiate my bean? What's with the interfaces? I'm not entirely sure if my bean should be stateful or stateless :\
Additional info:
I changed code in my servlet, from
UserManagerBean um = new UserManagerBean();
to
#EJB
private UserManagerBean um;
in the appropriate place. Now um is the NullPointer.
Quoting Referencing EJB3 Session Beans from non-EJB3 Beans from the JBoss documentation:
JBoss Application Server 4.2.2 implemented EJB3 functionality by way of an EJB MBean container running as a plugin in the JBoss Application Server. This had certain implications for application development.
The EJB3 plugin injects references to an EntityManager and #EJB references from one EJB object to another. However this support is limited to the EJB3 MBean and the JAR files it manages. Any JAR files which are loaded from a WAR (such as Servlets, JSF backing beans, and so forth) do not undergo this processing. The Java 5 Enterprise Edition standard specifies that a Servlet can reference a Session Bean through an #EJB annotated reference, this was not implemented in JBoss Application Server 4.2.2.
So even though the Java EE 5 specification stipulates a wider scope of the #EJB annotation, JBoss 4.2.2 doesn't support it. In fact JBoss 4.2.2 is a transitional version that doesn't claim full Java EE 5 compliance.
Consequently, either:
Stick with you actual version of JBoss but use a JDNI lookup to get your bean - or -
Swith to JBoss 5 AS that fully supports the entire Java 5 Enterprise Edition specification (but has horrible startup performances) - or -
Swith to another Java EE 5 application server like GlassFish v2 (or even v3) or WebLogic 10. I'd go with GFv3.
As Petar Minchev said in the comments above #EJB doesn't work in servlets with JBoss 4.2.
In your WAR (in the WEB-INF directory) you'll need to modify two files:
web.xml:
<ejb-local-ref>
<ejb-ref-name>ejb/UserManager</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local-home/>
<local>myPackage.UserManager</local>
</ejb-local-ref>
jboss-web.xml:
<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 2.3//EN" "http://www.jboss.org/j2ee/dtd/jboss-web_3_2.dtd">
<jboss-web>
<ejb-local-ref>
<ejb-ref-name>ejb/UserManager</ejb-ref-name>
<local-jndi-name>[earname]/UserManagerBean/local</local-jndi-name>
</ejb-local-ref>
</jboss-web>
You can then get an instance of your EJB by doing:
UserManagerBean um = (UserManager)new InitialContext().lookup( "java:comp/env/ejb/UserManager" );
As per the comments, it turns out that you indeed are using an appserver which doesn't support it at all -as I expected. To resolve this, you have 3 options:
Use "good old" XML config files.
Upgrade the server (there's already a stable 5.1.0).
Replace the server (I can recommend Glassfish v3 to be the most up-to-date).
To enable dependency injection on your project make sure that you have the file "beans.xml" and it is properly located.
For WAR packaging the location is src/main/webapp/WEB-INF/
For JAR and EAR packaging the location is src/main/resources/META-INF/
If you have several maven modules you must have it on each module.
More information about beans.xml

Categories

Resources