Do I need DataSource in JPA Hibernate project? - mysql

I am preparing some application with usage of JPA 2.0, Hibernate as provider, MySQL 5 as database, which will be deployed on JBoss AS 7.0.2.I have already configured some basics in persistence.xml and I came into some kind of trouble. I have noticed that some people also defines some specific DataSource on JBoss Management Console level.
My question is. Do I really need to worry about some DataSource or anything like that in Hibernate application?I thought it is important in old JDBC approach.In some books, where examples are shown, there is no such configuration in persistence.xml or hibernate.cfg.xml
Do I have to place mysql connector into JBOSS_HOME/standalone/deployments directory to use MySQL in my application?Here is content of my persistence.xml file:
<?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="SomeApp">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/somedb" />
<property name="hibernate.connection.username" value="" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
</persistence-unit>
</persistence>

Well, you can either access the database by:
providing the url/driver/password/etc. information in the persistence.xml using your jpa-provider properties (in your case hibernate.connection.*) or the JPA 2.0 standardised javax.persistence.jdbc.* ones - this basically looks like the example you've posted,
creating a Data Source in the ApplicationServer and just referring to it in the persistence.xml (through it's JNDI name you provide during creation) which might look similar to this (without the XML schema definition for the sake of brevity) :
<persistence>
<persistence-unit name="SomeApp">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/myDB</jta-data-source>
</persistence-unit>
</persistence>
What you're actually doing right now (with these properties) is using the JDBC.
I would definitely go with the creation of the Data Source in the ApplicationServer rather than providing it in the properties in persistence.xml. It allows you to dynamically change the end-database, it's type, credentials, manage connection pools, etc. without even touching your descriptor.
It's also safer, as the credentials are not written in the plain file left on your server.
As a side note, please remember that the javax.persistence.jdbc.* properties are a JPA provider must requirement for the Java SE environment, but it's optional for Java EE.
Hope that helps!

Do I have to place mysql connector into
JBOSS_HOME/standalone/deployments directory to use MySQL in my
application?
Yes you need to put Mysql J/connector for use it as JDBC Driver. Your application server (JBOss, Weblogic, Glassfish, etc) doesn't provide it because depend of the RDBMS that you are using (in this case Mysql) and the version of it.
In the case of JBoss 7 the JDBC driver can be installed into the container in one of two ways: either as a deployment or as a core module. For the pros/cons of both modes an detailed explanatio you can check the following documentation: http://community.jboss.org/wiki/DataSourceConfigurationInAS7

Related

Wildfly 10 persistence MySQL table not found

I have a REST service which access a MySQL database. I'm using Wildfly 10 and MySQL 5.7.12. I am trying to get the EntityManager as an injection and I get the following error when executing the find method for my Entity mapping the table content.
org.h2.jdbc.JdbcSQLException: Table "MYTABLE" not found; SQL statement:
In the RESTService class I have
#PersistenceContext(unitName="myUnit")
protected EntityManager entityManager;
and my persistence.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="2.1">
<persistence-unit name="myUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mytable" />
<property name="javax.persistence.jdbc.user" value="user" />
<property name="javax.persistence.jdbc.password" value="pass" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.archive.autodetection" value="class, hbm"/>
</properties>
</persistence-unit>
</persistence>
The issue is that if instead of using injection I retrieve the entity manager using the manual way everything works smothly.
EntityManagerFactory emFactory;
emFactory = Persistence.createEntityManagerFactory("myUnit");
EntityManager em = emFactory.createEntityManager();
Could you give me some hints on how to use the PersistenceContext? the code is somehow cleaner and I prefer to use it.
It looks like you 're getting the default datasource injected in your persistence Unit so I guess this depends on how the EntityManager is 'built'. One way to fix this is to create a datasource in WidFly and use it (through) its JNDI name in your persistence unit.
Feel free to report a bug http://issues.jboss.org/
You are setting up a RESOURCE_LOCAL persistence unit. You should configure it as such:
<persistence-unit transaction-type="RESOURCE_LOCAL">
In order to use a resource local persistence unit you cannot inject EntityManager, only EntityManagerFactory. You'll end up with a lot less plumbing if you switch to JTA datasource and let the server manage it.
If you absolutely don't want to edit standalone.xml, in WF8 anyway, you can drop yourdatasource-ds.xml file into your WEB-INF folder, or into the deployments directory alongside your .war file. There was talk of removing this from WF though so I don't know if it works in 10.x.

Connecting database with hibernate

I know thats a known problem and i made my research but still couldnt find a proper answer and what to do, so my last hope is here. The problem is, when i use phpAdmin i can connect and create my tables in m database. But when i run hibernates connection wizard, after entering the connection properties, if i press the test connection it gives me this error :
"Timeout expired. IDE unable to establish connection. Check your proxy settings or try again later. The server may be unavailable at the moment.   You may also want to make sure that your firewall is not blocking network traffic."
My hibernate.cfg.xml looks like this
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.11.83.2:3306</property>
<property name="hibernate.connection.username">admin1s6nbcM</property>
<property name="hibernate.connection.password">*******</property>
</session-factory>
</hibernate-configuration>
I m suspecting that there is something wrong with MySQL Java Connector library ;
dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
because i get this warning when i build my application:
Some problems were encountered while building the effective model for cardsystelefonbuch:cardsystelefonbuch:war:1.0
'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: mysql:mysql-connector-java:jar -> version 5.1.25 vs 5.1.30 # line 83, column 13
It is highly recommended to fix these problems because they threaten the stability of your build.
For this reason, future Maven versions might no longer support building such malformed projects.
Any ideas would be greatly appreciated !

Connecting to remote database server

I'm developing an application in a container managed environment (Java EE). Therefore, I shouldn't have to worry about handling and closing transactions. I simply inject the EntityManager:
#PersistenceContext(unitName = "WebApplication")
private EntityManager em;
And my corresponding 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="WebApplication" transaction-type="JTA">
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"></property>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://link-to-my-database.us-east-1.rds.amazonaws.com:3306/TestDB"></property>
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
However, this does not work. According to the JPA 2.0 specification, javax.persistence.jdbc.driver is "attended for use in Java SE environments." (Section 8.2.1.9; page 317). And even the jta-datasource and non-jta-datasource only "name the data source in the local environment" (Section 8.2.1.5; page 313).
Then how can I connect to a remote database server? Obviously, I can explicitly create an EntityManager but then I would be responsible for handling the transactions, then what's the point of being in a container managed environment? If it's possible to connect to a remote database server using JPA and a container managed environment, can you provide an example on how to do so?

ClassNotFoundException weblogic.jdbc.wrapper.JTSConnection with default persistence provider?

I'm a newbie to EE and I'm working on an application on Weblogic 12c. Data Source tests fine in the Admin Console. When the EJB tries to access it, it throws this ClassNotFoundException. I've done three hours of research and I know the issue is that some jar is not in the server's classpath, but I can't figure out which one!!! I'm using the default EclipseLink persistence provider and using MySQL Driver. BOTH of these come packaged with Weblogic (according to Oracle documentation) so I shouldn't have to explicitly add them to the classpath. And besides, adding them didn't work. Any other ideas?
Here's the 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="YLE_PU" transaction-type="JTA">
<jta-data-source>YLEDataSource</jta-data-source>
<class>com.yle.studentmodule.entity.Address</class>
<class>com.yle.studentmodule.entity.Contact</class>
<class>com.yle.studentmodule.entity.Semester</class>
<class>com.yle.studentmodule.entity.Student</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.cache.type.default" value="NONE"/>
</properties>
</persistence-unit>
Quote from WebLogic Documentation:
"In addition to the Oracle Thin Driver, the mySQL 5.0.x (mysql-connector-java-commercial-5.0.x-bin.jar) JDBC driver is installed with WebLogic Server.
This driver is installed in the WL_HOME\server\lib folder (where WL_HOME is the folder where WebLogic Server is installed) with weblogic.jar. The manifest in weblogic.jar lists this file so that it is loaded when weblogic.jar is loaded (when the server starts). Therefore, you do not need to add this JDBC driver to your CLASSPATH."
Thanks!
In other case,
Check your jdk version and bit
I solved that change to 64bit jdk
There can be another situation, that more than one class file (jars) are available at the server, which creates ambiguity. This situation also generates the same error.
My suggestion is to keep only one jar (related to JDBC) at your server.
I resolved the same issue in weblogic 12c with Oracle as DBMS.
In my case I had the .jar file of the Oracle driver inside the jdk/jre/lib/ext folder and another one inside weblogic folder as well. Removing the driver from the JDK folder solved my problem.

NetBeans, GlassFish and Hibernate JPA

On work, im using Eclipse, Jboss and Hibernate JPA. For a smaller, private project I like to use Netbeans, GlassFish and Hibernate JPA.
Problem: I want hibernate to generate the tables automagically - but it won't do that for me.
What i did:
First, i installed - obvious is obvious - Netbeans, Glassfish and a local MySQL-DB.
I created a JDBC-Connection for Glassfish:
url: jdbc:mysql://localhost:3306/myDatabase?zeroDateTimeBehavior=convertToNull
name: myDatabaseJDBC
Driver: com.mysql.jdbc.Driver
The connection seems fine, "testing" it resolved to a successful connection.
Now i created the persistance.xml like 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" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>myDatabaseJDBC</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
Then i added the required depoendencies to my Project (using maven) and the hibernate Plugin to Glassfish
What works: When ive created a table, in Netbeans i can Select New -> Other -> Persistance -> Entity Class from Database. The connection shows the tables, i select one, click okay, and i got the entity.
However i usually work the other way round and let hibernate generate my tables from the created entities... That whoever won't work. (It even looks like Hibernate is not even invoked, when building the project)
Did I miss any configuration step?
update: -------------
I wanted to test if hibernate is "active" in any way. So i created a simple entity, a controller and deployed the application with a single button.
public void doSth() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("primary");
EntityManager em = emf.createEntityManager();
CEntity c = new CEntity();
c.setName("Test");
em.persist(c);
}
first, i received an exception:
Caused by: org.hibernate.HibernateException: The chosen transaction strategy requires access to the JTA TransactionManager
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:376)
Overhere: hibernate, mysql, glassfish v3, and JTA datasource i found the solution to add
// For GlassFish:
hibernate.transaction.manager_lookup_class=org.hibernate.transaction.SunONETransactionManagerLookup
to the persistance.xml. The exception is now gone, but i received another one: Unknown Entity: CEntity.
I figured out, that hibernate can NOT find my entities. (Yes, i used javax.persistance.Entity and not the one from the hibernate namespace). However "adding" the entity manually to the persistance.xml solves the issue and also the automatic table-creation is invoked.
However, now im looking for the correct configuration, so adding every Entity to persistance.xml is NOT required.
I set <exclude-unlisted-classes>false</exclude-unlisted-classes> but hibernate seems to ignore that...
The key was to add:
<property name="hibernate.archive.autodetection" value="class"/>
to persistence.xml's properties-collection. After all:
<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">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>myDatabaseJDBC</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup"/>
<property name="hibernate.archive.autodetection" value="class"/>
</properties>
</persistence-unit>
</persistence>