Hibernate Tools reverse engineering with Gradle - java

When I was using Eclipse as my IDE, I used to use Hibernate Tools to reverse engineer a database to obtain my entities, complete with annotations.
I recently moved to IntelliJ IDEA, which I consider to be an overral better IDE, but unfortunately there isn't a port of Hibernate Tools for it, so I cannot generate my entities the way I used to. I know that IntelliJ IDEA has its own reverse engineer tool (the one accessible via Persistence->Generate Persistence Mapping->By Database Schema), but I found it to be somewhat buggy, sometimes generating entities which are plain wrong.
I know that Hibernate Tools can be also used from Ant. Is there a way to use it from Gradle, too?

I managed to use Hibernate Tools from Gradle, largely thanks to this question.
It turns out (I didn't know it) that Gradle is indeed capable of calling Ant tasks, so it is possible to use the preexisting Hibernate Tools Ant task to reverse engineer a database.
To do so, it is necessary to have a hibernate.cfg.xml file, which contains the configuration needed to tell the Ant ask how to access our database. This is an example:
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/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://localhost:3306/mydb
</property>
<property name="hibernate.connection.username">
username
</property>
<property name="hibernate.connection.password">
password
</property>
</session-factory>
</hibernate-configuration>
(IntelliJ may complain about this file, telling that it cannot find the driver, but this is ok, as they will be provided by Gradle during the execution)
This config file will be used by the Ant task called from Gradle. I put it in a new db folder, created in the project root.
The following needs to be added to the build.gradle file:
configurations {
reverseMap
}
dependencies {
//...your other dependencies...
reverseMap 'org.hibernate:hibernate-core:4.0.1.Final'
reverseMap 'org.hibernate:hibernate-tools:4.0.1.Final'
reverseMap 'org.slf4j:slf4j-simple:1.7.5'
reverseMap 'mysql:mysql-connector-java:5.1.48'
}
project.ext {
hibernateDestDir = file("$projectDir/src/main/java")
}
task reverseMap {
outputs.dir hibernateDestDir
doLast {
hibernateDestDir.exists() || hibernateDestDir.mkdirs()
ant {
taskdef(
name: 'hibernatetool',
classname: 'org.hibernate.tool.ant.HibernateToolTask',
classpath: configurations.reverseMap.asPath
)
hibernatetool(destdir: hibernateDestDir) {
jdbcconfiguration(
configurationfile: "$projectDir/db/hibernate.cfg.xml",
packagename: "com.me.models"
)
hbm2java(
jdk5: true,
ejb3: true
)
}
}
}
}
This code creates a new configuration called reverseMap, which can be used to declare the dependencies needed for the reverseMap task (hibernate-core,hibernate-tools and log4j are needed, while the driver should be the one needed for your DBMS).
The reverseMap code calls the Ant task, basically following the official guide. The part of interest is hbm2java, which is the actual exporter. The rest of the code is basically glue code for the Ant task and configuration.
The Gradle task can be called either from the command line (./gradlew reverseMap) or from IntelliJ.

Related

Pagination in MyBatis using PageHelper gives no improvement in time

I'm trying to use PageHelper plugin provided on this repo following the installation instructions provided here, but my problem is that I am unable to achieve better timings as compared to what I was getting without the plugin. I downloaded jars for pagehelper and jsqparser, added them to the build path of my project as well as added pagehelper in dependencies list in build.gradle of my project as:
dependencies {
compile fileTree(dir: 'lib', include: ['*.jar'])
compile 'com.github.pagehelper:pagehelper:3.2.1'
compile files("lib/jsqlparser-3.0.jar")
}
and added them to my build path as well. Then for the second step, I edited config org.mybatis.spring.SqlSessionFactoryBean as following:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="wrapperDataSource" />
<property name="configLocation" value="/WEB-INF/MapConfig.xml"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!-- config params as the following -->
<value>
helperDialect=mysql
reasonable=true
supportMethodsArguments=true
params=count=countSql
autoRuntimeDialect=true
</value>
</property>
</bean>
</array>
</property>
</bean>
where the first two properties were already present in this xml file. Now after making these changes, I build my project and run it using jetty by calling selectList in the following manner:
RowBounds rowBounds = new RowBounds(0, 100);
List<E> pendingRequests = getSqlSession().<E>selectList("fetchAllPendingRequests",inputData,rowBounds);
where E is the datatype of my results.
The problem is that the time I get for this function to fetch all the results using the PageHelper plugin is almost the same as that I get without using the plugin. Although when I go into the debugging mode, I see that in both the cases, the query from database is happening in different ways through different methods. While without using the plugin, the final query call is made using executor object in SimpleExecutor class, using the plugin the call is made from PageInterceptor class of the PageHelper repo. So the only conclusion I draw is it is unable to perform physical pagination despite making use of the plugin, but I could not understand the reasons for it.
Any help would be very much appreciated :)

org.hibernate.console.HibernateConsoleRuntimeException: NoClassDefFoundError

I am trying to configure hibernate in Eclipse but i am having some problems when i try to generate the Hibernate Code:
org.hibernate.console.HibernateConsoleRuntimeException: Received a
NoClassDefFoundError, probably the console configuration classpath is
incomplete or contains conflicting versions of the same class Received
a NoClassDefFoundError, probably the console configuration classpath
is incomplete or contains conflicting versions of the same class
org.hibernate.console.HibernateConsoleRuntimeException: Received a
NoClassDefFoundError, probably the console configuration classpath is
incomplete or contains conflicting versions of the same class Received
a NoClassDefFoundError, probably the console configuration classpath
is incomplete or contains conflicting versions of the same class
java.lang.NoClassDefFoundError:
org/apache/commons/collections/MultiMap
org/apache/commons/collections/MultiMap
java.lang.ClassNotFoundException:
org.apache.commons.collections.MultiMap cannot be found by
org.jboss.tools.hibernate.runtime.v_5_1_5.0.1.Final-v20160331-1852-B88
org.apache.commons.collections.MultiMap cannot be found by
org.jboss.tools.hibernate.runtime.v_5_1_5.0.1.Final-v20160331-1852-B88
This is how my projects libraries look like
And this is my hibernate.cfg.xml
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="ConexionHibernate">
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">hr</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">hr</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
</session-factory>
</hibernate-configuration>
Before i have it with a tons more of jar files, but looking in other topics i tried to delete them. Before i had this jars, just in case i deleted someone i should not.
Old version of my project library
Thank you in advance!
I already solve the problem.
First of all i downloaded again all the jars from the hibernate website http://hibernate.org/orm/downloads/, concretely the 5.1.1 version.
I added to my project all the jars, not just the ones from the required folder, as i did the first time. And finally i downgraded the Hibernate console version to 4.3 and whoala! its working!

best way to reverse engineer pojos using hibernate

What is the best (easiest) way to reverse-engineer POJOs from a database? I would like to generate probably 40 entity classes from tables, just to save a bunch of typing. I would like to use the Hibernate Tools toolset but all examples seem incomplete or contradictory - some reference using Ant tasks, some reference Maven plugins, and the Jboss site itself indicates that Hibernate Tools 4.x now seems to be an Eclipse plugin!
What is the "correct" way to do this, starting from scratch?
I actually wound up using an Ant task. If you have a situation where you need to reverse-engineer POJOs from a database, and you have no existing infrastructure in place, I believe the Ant method is best. I started with this excellent blog post and was able to cut and paste most of the code I needed. I found through experimentation that some additional JARs were needed and after some tweaking was able to generate the POJOs I needed in fairly short order.
This assumes that you know basic Java terminology and a little about Ant, and have both installed. Here are the steps.
You'll need to create two files (build.xml and hibernate.cfg.xml) and download some JARs. You may also need to download the Hibernate DTD files if you are behind a proxy or firewall (since Hibernate will try to go out and read the DTDs). That's it.
Create the following directories:
/myantproject
/lib
/src
In your "myantproject" directory create your build.xml file as follows:
<project name="antbuild" basedir="." default="gen_hibernate">
<taskdef name="hibernatetool"
classname="org.hibernate.tool.ant.HibernateToolTask">
<classpath>
<fileset dir="lib">
<include name="**/*.jar"/>
</fileset>
</classpath>
</taskdef>
<target name="gen_hibernate"
description="generate hibernate classes">
<hibernatetool>
<jdbcconfiguration
configurationfile="hibernate.cfg.xml"
packagename="com.mycompany.model"
detectmanytomany="true"
/>
<hbm2hbmxml destdir="src" />
<hbm2java destdir="src" />
</hibernatetool>
</target>
</project>
Also in the "myantproject" directory create your hibernate.cfg.xml file as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.ibm.as400.access.AS400JDBCDriver</property>
<property name="hibernate.connection.url">jdbc:as400://myserver;libraries=MYLIB;dateformat=iso;timeformat=iso;prompt=false;naming=system;transaction isolation=none</property>
<property name="hibernate.connection.username">myuser</property>
<property name="hibernate.connection.password">mypassword</property>
<property name="hibernate.dialect">org.hibernate.dialect.DB2400Dialect</property>
</session-factory>
</hibernate-configuration>
If you are behind a firewall/proxy, you can download the DTD change the DTD reference in the file to this (make sure you edit it to point to your actual file location):
"file:///mypath/myantproject/lib/hibernate-configuration-3.0.dtd"
You can then download the DTD from the original URL and stick it in your "lib" directory.
Here are the JARs I wound up with. With these JARs, you should be able to run this Ant task and it will reverse-engineer all the tables in the database you have pointed to in "hibernate.cfg.xml".
cglib-nodep-2.2.3.jar
commons-collections-3.2.1.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
freemarker-2.3.8.jar
hibernate-annotations-3.5.0-Final.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-configuration-3.0.dtd
hibernate-core-3.3.1.GA.jar
hibernate-entitymanager-4.2.0.Final.jar
hibernate-tools-3.2.3.GA.jar
jt400-6.6.jar
jtidy-r938.jar
log4j-1.2.16.jar
slf4j-api-1.7.5.jar
These come from various sources - most either from apache.org or hibernate.org. You will need your database JDBC JAR from your database vendor (in this case an AS400 connector jar from IBM) to connect to the database. I also needed to download these DTDs since I was behind a firewall:
hibernate-mapping-3.0.dtd
hibernate-reverse-engineering-3.0.dtd
Good luck!

How to substitute a variable with real value in a xml file , which is in another dependency jar file by Maven

We have a project called web-app1 and has a dependency on another jar file called core-app.jar which is provided by another team as a shared library , yet there is a hibernate.cfg.xml in this core-app.jar (inside of the jar), with content as below.
<hibernate-configuration>
<session-factory>
<property name="dialect">${hibernate.dialect}</property>
<property name="query.substitutions"><![CDATA[false 'N', true 'Y']]></property>
<property name="show_sql">false</property>
<property name="format_sql">false</property>
<property name="use_sql_comments">false</property>
<property name="generate_statistics">true</property>
<property name="hibernate.connection.release_mode">after_transaction</property>
<!-- Search Configurations -->
<property name="hibernate.search.default.directory_provider">org.hibernate.search.store.FSDirectoryProvider</property>
<property name="hibernate.search.default.indexBase">${lucene.index.home}</property>
<property name="hibernate.search.default.batch.merge_factor">10</property>
<property name="hibernate.search.default.batch.max_buffered_docs">10</property>
</session-factory>
</hibernate-configuration>
As we see in the Search Configurations section, there is a variable ${lucene.index.home} that should be replaced by other projects on different OS platform,
so the question, does maven provide a way to filter a dependency jar file and filter the content? any plugins ? war:war , unzip ? dependencies ? I couldn't figure a fast way to do that. it looks to me , no matter what plugin would be adopted, the plugin needs to do 4 things basically.
1 unpack the jar in
process-resources phase.
2 substitute the ${var} with
value defined in profile.
3 pack it again back into a jar.
4 need to copy it back from the
packing/unpacking workspace back to
the maven process path ??
did anyone run into this similar requirement before.
thanks
I would assume that those values are meant to be set at runtime, likely as VM arguments. It doesn't make sense to provide a jar file that has to be modified to be able to be used.
If you really really REALLY have to do filtering at build time for configuration purposes, those configuration files should be filtered, NOT your dependencies. Then, you should either bundle said file into multiple artifacts (assuming of course you are targeting multiple environments), or be provided outside the built artifact as an externalized resource.

No Persistence provider for EntityManager named

I have my persistence.xml with the same name using TopLink under the META-INF directory.
Then, I have my code calling it with:
EntityManagerFactory emfdb = Persistence.createEntityManagerFactory("agisdb");
Yet, I got the following error message:
2009-07-21 09:22:41,018 [main] ERROR - No Persistence provider for EntityManager named agisdb
javax.persistence.PersistenceException: No Persistence provider for EntityManager named agisdb
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:89)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:60)
Here is the persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="agisdb">
<class>com.agis.livedb.domain.AddressEntity</class>
<class>com.agis.livedb.domain.TrafficCameraEntity</class>
<class>com.agis.livedb.domain.TrafficPhotoEntity</class>
<class>com.agis.livedb.domain.TrafficReportEntity</class>
<properties>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/agisdb"/>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="toplink.jdbc.user" value="root"/>
<property name="toplink.jdbc.password" value="password"/>
</properties>
</persistence-unit>
</persistence>
It should have been in the classpath. Yet, I got the above error.
Put the "hibernate-entitymanager.jar" in the classpath of application.
For newer versions, you should use "hibernate-core.jar" instead of the deprecated hibernate-entitymanager
If you are running through some IDE, like Eclipse: Project Properties -> Java Build Path -> Libraries.
Otherwise put it in the /lib of your application.
After <persistence-unit name="agisdb">, define the persistence provider name:
<provider>org.hibernate.ejb.HibernatePersistence</provider>
Make sure that the persistence.xml file is in the directory: <webroot>/WEB-INF/classes/META-INF
Faced the same issue and couldn't find solution for quite a long time. In my case it helped to replace
<provider>org.hibernate.ejb.HibernatePersistence</provider>
with
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
Took solution from here
I needed this in my pom.xml file:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.6.Final</version>
</dependency>
There is another point: If you face this problem within an Eclipse RCP environment, you might have to change the Factory generation from Persistence.createEntityManagerFactory to new PersistenceProvider().createEntityManagerFactory
see ECF for a detailed discussion on this.
Maybe you defined one provider like <provider>org.hibernate.ejb.HibernatePersistence</provider> but referencing another one in jar. That happened with me: my persistence.xml provider was openjpa but I was using eclipselink in my classpath.
Hope this help!
Quick advice:
check if persistence.xml is in your classpath
check if hibernate provider is in your classpath
With using JPA in standalone application (outside of JavaEE), a persistence provider needs to be specified somewhere. This can be done in two ways that I know of:
either add provider element into the persistence unit: <provider>org.hibernate.ejb.HibernatePersistence</provider> (as described in correct answere by Chris: https://stackoverflow.com/a/1285436/784594)
or provider for interface javax.persistence.spi.PersistenceProvider must be specified as a service, see here: http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html (this is usually included when you include hibernate,or another JPA implementation, into your classpath
In my case, I found out that due to maven misconfiguration, hibernate-entitymanager jar was not included as a dependency, even if it was a transient dependency of other module.
If you are using Eclipse make sure that exclusion pattern does not remove your persistence.xml from source folders on build path.
Go to Properties -> Java Build Path -> Source tab
Check your exclusion pattern which is located atMyProject/src/main/java -> Excluded: <your_pattern>tree node
Optionally, set it to Excluded: (None) by selecting the node and clicking Edit... button on the left.
I'm some years late to the party here but I hit the same exception while trying to get Hibernate 3.5.1 working with HSQLDB and a desktop JavaFX program. I got it to work with the help of this thread and a lot of trial and error. It seems you get this error for a whole variety of problems:
No Persistence provider for EntityManager named mick
I tried building the hibernate tutorial examples but because I was using Java 10 I wasn't able to get them to build and run easily. I gave up on that, not really wanting to waste time fixing its problems. Setting up a module-info.java file (Jigsaw) is another hairball many people haven't discovered yet.
Somewhat confusing is that these (below) were the only two files I needed in my build.gradle file. The Hibernate documentation isn't clear about exactly which Jars you need to include. Entity-manager was causing confusion and is no longer required in the latest Hibernate version, and neither is javax.persistence-api. Note, I'm using Java 10 here so I had to include the jaxb-api, to get around some xml-bind errors, as well as add an entry for the java persistence module in my module-info.java file.
Build.gradle
// https://mvnrepository.com/artifact/org.hibernate/hibernate-core
compile('org.hibernate:hibernate-core:5.3.1.Final')
// https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api
compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
Module-info.java
// Used for HsqlDB - add the hibernate-core jar to build.gradle too
requires java.persistence;
With hibernate 5.3.1 you don't need to specify the provider, below, in your persistence.xml file. If one is not provided the Hibernate provider is chosen by default.
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
The persistence.xml file should be located in the correct directory so:
src/main/resources/META-INF/persistence.xml
Stepping through the hibernate source code in the Intellij debugger, where it checks for a dialect, also threw the exact same exception, because of a missing dialect property in the persistence.xml file. I added this (add the correct one for your DB type):
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
I still got the same exception after this, so stepping through the debugger again in Intellij revealed the test entity I was trying to persist (simple parent-child example) had missing annotations for the OneToMany, ManyToOne relationships. I fixed this and the exception went away and my entities were persisted ok.
Here's my full final persistence.xml:
<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="mick" transaction-type="RESOURCE_LOCAL">
<description>
Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
</description>
<!-- Provided in latest release of hibernate
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
-->
<class>com.micks.scenebuilderdemo.database.Parent</class>
<class>com.micks.scenebuilderdemo.database.Child</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbc.JDBCDriver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:hsqldb:file:./database/database;DB_CLOSE_DELAY=-1;MVCC=TRUE"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
</properties>
</persistence-unit>
</persistence>
I probably wasted about half a day on this gem. My advice would be to start very simple - a single test entity with one or two fields, as it seems like this exception can have many causes.
Corner case: if you are using m2Eclipse, it automatically puts in excludes on your resources folders. Then when you try to run tests inside eclipse, the subsequent absence of persistence.xml will produce this error.
Make sure you have created persistence.xml file under the 'src' folder. I created under the project folder and that was my problem.
If you're using Maven, it could be that it is not looking at the right place for the META-INF folder. Others have mentioned copying the folder, but another way that worked for me was to tell Maven where to look for it, using the <resources> tag. See: http://maven.apache.org/plugins/maven-resources-plugin/examples/resource-directory.html
It happenes when the entity manager is trying to point to many persistence units. Do the following steps:
open the related file in your editor (provided your project has been closed in your IDE)
delete all the persistence and entity manager related code
save the file
open the project in your IDE
now bind the db or table of your choice
I faced the same problem, but on EclipseLink version 2.5.0.
I solved my problem by adding yet another jar file which was necessarily (javax.persistence_2.1.0.v201304241213.jar.jar);
Jars needed:
- javax.persistence_2.1.0.v201304241213.jar
- eclipselink.jar
- jdbc.jar (depending on the database used).
I hope this helps.
I also had this error but the issue was the namespace uri in the persistence.xml.
I replaced http://xmlns.jcp.org/xml/ns/persistence to http://java.sun.com/xml/ns/persistence and the version 2.1 to 2.0.
It's now working.
You need to add the hibernate-entitymanager-x.jar in the classpath.
In Hibernate 4.x, if the jar is present, then no need to add the org.hibernate.ejb.HibernatePersistence in persistence.xml file.
In my case, previously I use idea to generate entity by database schema, and the persistence.xml is automatically generated in src/main/java/META-INF,and according to https://stackoverflow.com/a/23890419/10701129, I move it to src/main/resources/META-INF, also marked META-INF as source root. It works for me.
But just simply marking original META-INF(that is, src/main/java/META-INF) as source root, doesn't work, which confuses me.
and this is the structre:
The question has been answered already, but just wanted to post a tip that was holding me up. This exception was being thrown after previous errors. I was getting this:
property toplink.platform.class.name is deprecated, property toplink.target-database should be used instead.
Even though I had changed the persistence.xml to include the new property name:
<property name="toplink.target-database" value="oracle.toplink.platform.database.oracle.Oracle10Platform"/>
Following the message about the deprecated property name I was getting the same PersistenceException like above and a whole other string of exceptions. My tip: make sure to check the beginning of the exception sausage.
There seems to be a bug in Glassfish v2.1.1 where redeploys or undeploys and deploys are not updating the persistence.xml, which is being cached somewhere. I had to restart the server and then it worked.
In an OSGi-context, it's necessary to list your persistence units in the bundle's MANIFEST.MF, e.g.
JPA-PersistenceUnits: my-persistence-unit
Otherwise, the JPA-bundle won't know your bundle contains persistence units.
See http://wiki.eclipse.org/EclipseLink/Examples/OSGi/Developing_with_EclipseLink_OSGi_in_PDE .
You need the following jar files in the classpath:
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.0.1.Final.jar
hibernate-entitymanager.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
javassist-3.9.0.jar
jboss-logging-3.1.1.GA.jar
jta-1.1.jar
slf4j-api-1.5.8.jar
xxx-jdbc-driver.jar
I just copied the META-INF into src and worked!
Hibernate 5.2.5
Jar Files Required in the class path. This is within a required folder of Hibernate 5.2.5 Final release. It can be downloaded from http://hibernate.org/orm/downloads/
antlr-2.7.7
cdi-api-1.1
classmate-1.3.0
dom4j-1.6.1
el-api-2.2
geronimo-jta_1.1_spec-1.1.1
hibernate-commons-annotation-5.0.1.Final
hibernate-core-5.2.5.Final
hibernate-jpa-2.1-api-1.0.0.Final
jandex-2.0.3.Final
javassist-3.20.0-GA
javax.inject-1
jboss-interceptor-api_1.1_spec-1.0.0.Beta1
jboss-logging-3.3.0.Final
jsr250-api-1.0
Create an xml file "persistence.xml" in
YourProject/src/META-INF/persistence.xml
persistence.xml
<?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="sample">
<class>org.pramod.data.object.UserDetail</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/hibernate_project"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="root"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<property name="hibernate.archive.autodetection" value="true"/>
</properties>
</persistence-unit>
please note down the information mentioned in the < persistance > tag and version should be 2.1.
please note the name < persistance-unit > tag, name is mentioned as "sample". This name needs to be used exactly same while loading your
EntityManagerFactor = Persistance.createEntityManagerFactory("sample");. "sample" can be changed as per your naming convention.
Now create a Entity class. with name as per my example UserDetail, in the package org.pramod.data.object
UserDetail.java
package org.pramod.data.object;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "user_detail")
public class UserDetail {
#Id
#Column(name="user_id")
private int id;
#Column(name="user_name")
private String userName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Override
public String toString() {
return "UserDetail [id=" + id + ", userName=" + userName + "]";
}
}
Now create a class with main method.
HibernateTest.java
package org.pramod.hibernate;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.pramod.data.object.UserDetail;
public class HibernateTest {
private static EntityManagerFactory entityManagerFactory;
public static void main(String[] args) {
UserDetail user = new UserDetail();
user.setId(1);
user.setUserName("Pramod Sharma");
try {
entityManagerFactory = Persistence.createEntityManagerFactory("sample");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist( user );
entityManager.getTransaction().commit();
System.out.println("successfull");
entityManager.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output will be
UserDetail [id=1, userName=Pramod Sharma]
Hibernate: drop table if exists user_details
Hibernate: create table user_details (user_id integer not null, user_name varchar(255), primary key (user_id))
Hibernate: insert into user_details (user_name, user_id) values (?, ?)
successfull
If there are different names in Persistence.createEntityManagerFactory("JPAService") in different classes than you get the error. By refactoring it is possible to get different names which was in my case. In one class the auto-generated Persistence.createEntityManagerFactory("JPAService")in private void initComponents(), ContactsTable class differed from Persistence.createEntityManagerFactory("JPAServiceExtended") in DBManager class.
Mine got resolved by adding info in persistence.xml e.g. <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> and then making sure you have the library on classpath e.g. in Maven add dependency like
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
</dependency>
Verify the peristent unit name
<persistence-unit name="com.myapp.model.jpa"
transaction-type="RESOURCE_LOCAL">
public static final String PERSISTENCE_UNIT_NAME = "com.myapp.model.jpa";
Persistence.createEntityManagerFactory(**PERSISTENCE_UNIT_NAME**);
In my case it was about mistake in two properties as below. When I changed them ‘No Persistence provider for EntityManager named’ disappered.
So you could try test connection with your properties to check if everything is correct.
<property name="javax.persistence.jdbc.url" value="...”/>
<property name="javax.persistence.jdbc.password" value="...”/>
Strange error, I was totally confused because of it.
Try also copying the persistence.xml manually to the folder <project root>\bin\META-INF. This fixed the problem in Eclipse Neon with EclipseLink 2.5.2 using a simple plug-in project.
Had the same issue, but this actually worked for me :
mvn install -e -Dmaven.repo.local=$WORKSPACE/.repository.
NB : The maven command above will reinstall all your project dependencies from scratch. Your console will be loaded with verbose logs due to the network request maven is making.
You have to use the absolute path of the file otherwise this will not work. Then with that path we build the file and pass it to the configuration.
#Throws(HibernateException::class)
fun getSessionFactory() : SessionFactory {
return Configuration()
.configure(getFile())
.buildSessionFactory()
}
private fun getFile(canonicalName: String): File {
val absolutePathCurrentModule = System.getProperty("user.dir")
val pathFromProjectRoot = absolutePathCurrentModule.dropLastWhile { it != '/' }
val absolutePathFromProjectRoot = "${pathFromProjectRoot}module-name/src/main/resources/$canonicalName"
println("Absolute Path of secret-hibernate.cfg.xml: $absolutePathFromProjectRoot")
return File(absolutePathFromProjectRoot)
}
GL
Source

Categories

Resources