I am trying to run a little Maven test program using NetBeans. Now the NetBeans-given code works perfectly fine with Maven. Compiling, running, all good. But when I change anything, like adding an FXML-File or adding JPA persistence, I then get errors when starting the program. Compiling seems to work, but I can't start the program. I expect the error to be somewhere in the configuration of Maven, but I can't find it. The code by itself should work just fine.
Ok, to show you guys what exactly I mean, here is the code. I just add a JPA-persistence to a MySQL-Database. After adding the program doesn't run anymore.
App.java:
package com.myproject.mavenproject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello new World!" );
EntityManagerFactory emf = Persistence.createEntityManagerFactory( "GlassesPU" );
try {
EntityManager em = emf.createEntityManager();
EntityTransaction tx = null;
try {
tx = em.getTransaction();
tx.begin();
Hund hund = new Hund();
hund.setFormerName("Albert");
hund.setNewName("Einstein");
em.persist(hund);
//em.persist( entity1 );
//em.merge( entity2 );
//em.find( MyEntity.class, id );
tx.commit();
} catch( RuntimeException ex ) {
if( tx != null && tx.isActive() ) tx.rollback();
throw ex;
} finally {
em.close();
}
} finally {
emf.close();
}
}
}
Hund.java:
package com.myproject.mavenproject;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Hund implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String formerName;
private String newName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFormerName() {
return formerName;
}
public void setFormerName(String formerName) {
this.formerName = formerName;
}
public String getNewName() {
return newName;
}
public void setNewName(String newName) {
this.newName = newName;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Hund)) {
return false;
}
Hund other = (Hund) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.myproject.mavenproject.Hund[ id=" + id + " ]";
}
}
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.myproject_MavenProject_jar_1.0-SNAPSHOTPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.myproject.mavenproject.Hund</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/glasses?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.password" value="mypassword"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myproject</groupId>
<artifactId>MavenProject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MavenProject</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.5.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
Error message:
cd /home/myuser/NetBeansProjects/MavenProject; JAVA_HOME=/usr/lib/jvm/jdk1.7.0_51 /home/myuser/netbeans-7.4/java/maven/bin/mvn "-Dexec.args=-classpath %classpath com.myproject.mavenproject.App" -Dexec.executable=/usr/lib/jvm/jdk1.7.0_51/bin/java org.codehaus.mojo:exec-maven-plugin:1.2.1:exec
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Scanning for projects...
------------------------------------------------------------------------
Building MavenProject 1.0-SNAPSHOT
------------------------------------------------------------------------
--- exec-maven-plugin:1.2.1:exec (default-cli) # MavenProject ---
Hello new World!
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named GlassesPU
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at com.myproject.mavenproject.App.main(App.java:18)
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 0.891s
Finished at: Mon Feb 03 21:35:25 CET 2014
Final Memory: 5M/111M
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project MavenProject: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]
To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.
For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
Anyone has an idea what the problem could be?
There is no problem with Maven. It's only reporting the error. It says that it can't find a persistence provider called "GlassesPU".
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named GlassesPU
Your persistence.xml has another name:
<persistence-unit name="com.myproject_MavenProject_jar_1.0-SNAPSHOTPU" ... >
Try changing it to "GlassesPU":
<persistence-unit name="GlassesPU" ...>
If Maven complains again, it will probably be due to something else.
Related
when I'm deploying my simple project to Heroku I'm getting a maven-plugin error
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin
my code is very simple it's one entity class and restController class, when I run my project on my pc it working but the deployment failed.
my class
package com.hosting.hostingTest;
public class BucketList {
private long id;
private String name;
public BucketList(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
my rest controller
package com.hosting.hostingTest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class BucketListController {
private List<BucketList> myBucketList = new ArrayList<>();
private final AtomicLong counter = new AtomicLong();
public BucketListController(){
myBucketList.add(new BucketList(counter.incrementAndGet(), "Visit Colosseum in Rome"));
}
#GetMapping(value = "/")
public ResponseEntity index() {
return ResponseEntity.ok(myBucketList);
}
#GetMapping(value = "/bucket")
public ResponseEntity getBucket(#RequestParam(value="id") Long id) {
BucketList itemToReturn = null;
for(BucketList bucket : myBucketList){
if(bucket.getId() == id)
itemToReturn = bucket;
}
if(itemToReturn == null){
return ResponseEntity.ok("No bucket found with id " + id);
}else {
return ResponseEntity.ok(itemToReturn);
}
}
#PostMapping(value = "/")
public ResponseEntity addToBucketList(#RequestParam(value="name") String name) {
myBucketList.add(new BucketList(counter.incrementAndGet(), name));
return ResponseEntity.ok(myBucketList);
}
#PutMapping(value = "/")
public ResponseEntity updateBucketList(#RequestParam(value="name") String name, #RequestParam(value="id") Long id) {
myBucketList.forEach(bucketList -> {
if(bucketList.getId() == id){
bucketList.setName(name);
}
});
return ResponseEntity.ok(myBucketList);
}
#DeleteMapping(value = "/")
public ResponseEntity removeBucketList(#RequestParam(value="id") Long id) {
BucketList itemToRemove = null;
for(BucketList bucket : myBucketList){
if(bucket.getId() == id)
itemToRemove = bucket;
}
myBucketList.remove(itemToRemove);
return ResponseEntity.ok(myBucketList);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.hosting</groupId>
<artifactId>hostingTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hostingTest</name>
<description>Demo project for Spring Boot</description>
<packaging>jar</packaging>
<properties>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
the error :
[INFO] Compiling 3 source files to /tmp/build_a3c8365b/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.228 s
[INFO] Finished at: 2020-08-12T12:41:17Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project hostingTest: Compilation failure -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
! ERROR: Failed to build app with Maven
We're sorry this build is failing! If you can't find the issue in application code,
please submit a ticket so we can help: https://help.heroku.com/
! Push rejected, failed to compile Java app.
! Push failed
I am using jdk 13 but I want to create entity and write to database its.
and I added project->run configurations->arguments->VM Arguments
--add-modules java.xml.bind
then I ran the project but , I am getting this error :
Error occurred during initialization of boot layer
java.lang.module.FindException: Module java.xml.bind not found
I dont know, I am getting error why.I suppose my jdk is problem.But I dont know exactly.what should I do?
Test.java
package com.kerem.blog;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Test {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("MyPersistenceUnit");
EntityManager manager = factory.createEntityManager();
Data data = new Data();
data.setDataName("Kerem");
data.setDataValue(23.2);
manager.getTransaction().begin();
manager.persist(data);
manager.getTransaction().commit();
manager.close();
}
}
Data.java
package com.kerem.blog;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Data {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private long dataId;
private String dataName;
private double dataValue;
public long getDataId() {
return dataId;
}
public void setDataId(long dataId) {
this.dataId = dataId;
}
public String getDataName() {
return dataName;
}
public void setDataName(String dataName) {
this.dataName = dataName;
}
public double getDataValue() {
return dataValue;
}
public void setDataValue(double dataValue) {
this.dataValue = dataValue;
}
}
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="MyPersistenceUnit">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/testdb?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=Turkey" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password"
value="kerem2112" />
<property
name="javax.persistence.schema-generation.database.action"
value="create" />
</properties>
</persistence-unit>
</persistence>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.keremsarmis</groupId>
<artifactId>blogbasic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.6.Final</version>
</dependency>
</dependencies>
</project>
I'm currently in the process of updating a large project from Hibernate 5.1 to Hibernate 5.2.17 and I'm running into an issue that I'm struggling to resolve.
We have a suite of tests that are testing our DAOs using the H2 in-memory database, but some tests have started to fail on the updated version of Hibernate.
Some of the tests attempt to delete a null entity from the persistence context and expect the operation to fail with an IllegalArgumentException. With the new version of Hibernate the exception is still thrown as expected, but the transaction is no longer being rolled back and is being left active, and is consequently causing subsequent tests to fail because there's already an active transaction. Stack trace included below:
java.lang.AssertionError: Transaction is still active when it should have been rolled back.
at org.junit.Assert.fail(Assert.java:88)
at hibernatetest.persistence.HibernateTestDAOTest.testDeleteDetachedEntity(HibernateTestDAOTest.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
While investigating I noticed a similar difference in behaviour when attempting to delete a detached entity as well. I have been able to recreate the behaviour in a small, standalone project that can be found here. The project also includes configuration in the pom.xml (commented out) for running against Hibernate 5.0.10, where the tests pass with no issue and the failed transaction is correctly rolled-back.
While I haven't been able to recreate the error deleting a null entity, I have managed to recreate it with a detached entity, and I'm hoping the answer to why this is happening will help guide me to why it's also failing with null in the real code.
Are we doing something wrong here, or is this an issue with Hibernate itself?
Code also included below:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>HibernateTest</groupId>
<artifactId>HibernateTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<maven.compiler.version>3.7.0</maven.compiler.version>
<!-- Uncomment this property to run as Hibernate 5.0.10 -->
<!-- <hibernate.core.version>5.0.10.Final</hibernate.core.version> -->
<!-- Uncomment this property to run as Hibernate 5.2.17 -->
<hibernate.core.version>5.2.17.Final</hibernate.core.version>
<junit.version>4.12</junit.version>
<h2.version>1.4.197</h2.version>
<javaee.api.version>7.0</javaee.api.version>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.core.version}</version>
</dependency>
<!-- Uncomment these dependencies to run using Hibernate 5.0.10 -->
<!--
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>${hibernate.core.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.core.version}</version>
<scope>test</scope>
</dependency>
-->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee.api.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
HibernateTest.java (entity class):
package hibernatetest.persistence;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
#Entity
#Table(name = "hibernate_test")
public class HibernateTest {
#Id
#Column(name = "id")
#Type(type = "uuid-char")
private UUID id;
public HibernateTest(final UUID id) {
this.id = id;
}
}
HibernateTestDAO.java
package hibernatetest.persistence;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class HibernateTestDAO {
#PersistenceContext(unitName = "hibernate-test")
private EntityManager entityManager;
public void delete(final HibernateTest entity) {
entityManager.remove(entity);
}
}
EntityManagerRule.java (JUnit Rule to provide the entity manager for the tests):
package hibernatetest.persistence;
import java.lang.reflect.Field;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.rules.ExternalResource;
public class EntityManagerRule extends ExternalResource {
private EntityManagerFactory emFactory;
private EntityManager em;
#Override
protected void before() {
emFactory = Persistence.createEntityManagerFactory("hibernate-test");
em = emFactory.createEntityManager();
}
#Override
protected void after() {
if (em != null) {
em.close();
}
if (emFactory != null) {
emFactory.close();
}
}
public HibernateTestDAO initDAO() {
final HibernateTestDAO dao = new HibernateTestDAO();
try {
injectEntityManager(dao);
} catch (Exception e) {
e.printStackTrace();
}
return dao;
}
public EntityManager getEntityManager() {
return em;
}
public void persist(final Object entity) {
final EntityTransaction transaction = em.getTransaction();
transaction.begin();
try {
em.persist(entity);
} catch (Exception e) {
transaction.rollback();
throw e;
}
transaction.commit();
}
private void injectEntityManager(final HibernateTestDAO dao) throws Exception {
final Field emField = dao.getClass().getDeclaredField("entityManager");
emField.setAccessible(true);
emField.set(dao, em);
}
}
HibernateTestDAOTest.java:
package hibernatetest.persistence;
import static org.junit.Assert.fail;
import java.util.UUID;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public class HibernateTestDAOTest {
#Rule
public EntityManagerRule rule = new EntityManagerRule();
private HibernateTestDAO dao;
#Before
public void setup() {
dao = rule.initDAO();
}
#Test
public void testDeleteNullEntity() {
HibernateTest entity = null;
try {
dao.delete(entity);
} catch (IllegalArgumentException e) {
if (rule.getEntityManager().getTransaction().isActive()) {
fail("Transaction is still active when it should have been rolled back.");
}
}
}
#Test
public void testDeleteDetachedEntity() {
HibernateTest entity = new HibernateTest(UUID.randomUUID());
rule.persist(entity);
rule.getEntityManager().detach(entity);
try {
dao.delete(entity);
} catch (IllegalArgumentException e) {
if (rule.getEntityManager().getTransaction().isActive()) {
fail("Transaction is still active when it should have been rolled back.");
}
}
}
}
persistence.xml from src/test/resources/META-INF:
<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="hibernate-test" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>hibernatetest.persistence.HibernateTest</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:test;INIT=create schema if not exists test\;runscript from 'classpath:/populate.sql';DB_CLOSE_DELAY=-1;"/>
<property name="javax.persistence.validation.mode" value="none"/>
</properties>
</persistence-unit>
</persistence>
populate.sql from src/test/resources:
CREATE TABLE IF NOT EXISTS hibernate_test (
id UUID NOT NULL
);
Nothing in the spec states that when a call to EntityManager#remove fails that the persistence provider should rollback the existing transaction, that just makes no sense.
If you look at all the examples in the Hibernate test suite, you'll notice this behavior:
EntityManager entityManager = getOrCreateEntityManager();
try {
entityManager.getTransaction().begin();
// do something
entityManager.getTransaction().commit();
}
catch ( Exception e ) {
if ( entityManager != null && entityManager.getTransaction.isActive() ) {
entityManager.getTransaction().rollback();
}
throw e;
}
finally {
if ( entityManager != null ) {
entityManager.close();
}
}
If your tests worked previously and no longer do in the same way, I'm not sure I'd necesssarily say that is a bug as the code which you've supplied above does not conform to what I have shown here with properly handling the rollback in user code unless you have spring or some other framework at play which you haven't illustrated.
But if you feel there is a regression between 5.1 and 5.2, you're welcomed to open a JIRA and report it with your reproducable test use case and we can do further investigation.
One key point to remember is that 5.2.x introduced the merging of the JPA artifact hibernate-entitymanager into hibernate-core proper, so there could be a regression here with that but its extremely unlikely.
I have a piece of example code:
public class JpaTest {
private EntityManagerFactory emf;
private void setUp() throws Exception {
emf = Persistence.createEntityManagerFactory("testPU");
}
private void tearDown() {
emf.close();
}
private void save() {
EntityManager em = null;
EntityTransaction tx = null;
try {
em = emf.createEntityManager();
tx = em.getTransaction();
tx.begin();
em.persist(new Event("First event", new Date()));
em.persist(new Event("A follow up event", new Date()));
throw new RuntimeException();
} catch (Exception e) {
if (tx != null) tx.rollback();
} finally {
if (em != null) em.close();
}
}
public static void main(String[] args) throws Exception {
JpaTest test = new JpaTest();
test.setUp();
test.save();
test.tearDown();
}
}
The database is MySQL.
The code persists Event entity into the database and than throws an Exception. I expect tx.rollback() to delete the changes made into the database, but this command never works and the data remains in the table:
The question is why tx.rollback() fails and how to delete changes made in the database if transaction throws an Exception?
UPDATED:
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="testPU">
<class>exampleForTestingJpa.Event</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url"
value="url here..."/>
<property name="javax.persistence.jdbc.user" value="username here..."/>
<property name="javax.persistence.jdbc.password" value="password here..."/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.autocommit" value="false"/>
</properties>
</persistence-unit>
</persistence>
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>example</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
</dependencies>
</project>
Add this to your persistence.xml
<property name="hibernate.connection.autocommit" value="false"/>
Maybe autocommit is enabled ? MySQL manual states that autocommit is enabled by default.
If thats the problem, you surely will not be the first who stumbled over that ;-)
As other users said, it is probably a auto-commit issue since according to the MySQL documentation :
In InnoDB ...
By default, MySQL starts the session for each new connection with
autocommit enabled, so MySQL does a commit after each SQL statement if
that statement did not return an error. If a statement returns an
error, the commit or rollback behavior depends on the error. See
Section 14.21.4, “InnoDB Error Handling”.
Besides, you should not store the Transaction object in a variable.
At each time you want to invoke a Transaction method, get the Transaction object from the EntityManager.
So replace :
tx = em.getTransaction();
tx.begin();
by :
em.getTransaction().begin();
And replace tx.rollback(); by em.getTransaction().rollback();
The Transaction object stored in the EntityManager may be serialized and so have a new reference during transaction processing.
For example, look at the serialization method of AbstractEntityManagerImpl:
public class org.hibernate.jpa.spi.AbstractEntityManagerImpl{
...
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
tx = new TransactionImpl( this );
}
...
}
The problem with not rolling transaction back was caused by MyISAM. With InnoDB rollback works fine.
I have seen a lot of questions but the answers are not satisfying my problem...
I start with Spring Boot and I am completely lost.
The error is :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: pack.datas.entities.Degree
/// others lines
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: pack.datas.entities.Degree
The entry point :
package pack;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
#RestController
#EntityScan
public class CandidatesRecruitmentApplication {
public static void main(String[] args) {
SpringApplication.run(CandidatesRecruitmentApplication.class, args);
}
}
The classes :
package pack.datas;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Component;
#Component
#Configuration
#EnableJpaRepositories
public class DatasFactory {
private DataSource dataSource;
public DatasFactory() {
super();
}
#Bean
#ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
if(this.dataSource == null)
return this.dataSource = DataSourceBuilder.create().build();
else
return this.dataSource;
}
package pack.datas.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Table;
import org.springframework.data.annotation.Id;
#Entity
#Table(name = "degree")
public class Degree implements Serializable {
private static final long serialVersionUID = -8900492704842756948L;
#Id
#GeneratedValue
#Column(name = "pk_id")
private Integer id;
#Column(name = "degree_i")
private Integer degreeId;
#Column(name = "degree_s_en")
private String degreeEn;
#Column(name = "degree_s_fr")
private String degreeFr;
protected Degree() {
}
public Degree(Integer id, Integer degreeId, String degreeEn, String degreeFr) {
super();
this.id = id;
this.degreeId = degreeId;
this.degreeEn = degreeEn;
this.degreeFr = degreeFr;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDegreeId() {
return degreeId;
}
public void setDegreeId(Integer degreeId) {
this.degreeId = degreeId;
}
public String getDegreeEn() {
return degreeEn;
}
public void setDegreeEn(String degreeEn) {
this.degreeEn = degreeEn;
}
public String getDegreeFr() {
return degreeFr;
}
public void setDegreeFr(String degreeFr) {
this.degreeFr = degreeFr;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((degreeEn == null) ? 0 : degreeEn.hashCode());
result = prime * result + ((degreeFr == null) ? 0 : degreeFr.hashCode());
result = prime * result + ((degreeId == null) ? 0 : degreeId.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Degree other = (Degree) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (degreeEn == null) {
if (other.degreeEn != null)
return false;
} else if (!degreeEn.equals(other.degreeEn))
return false;
if (degreeFr == null) {
if (other.degreeFr != null)
return false;
} else if (!degreeFr.equals(other.degreeFr))
return false;
if (degreeId == null) {
if (other.degreeId != null)
return false;
} else if (!degreeId.equals(other.degreeId))
return false;
return true;
}
#Override
public String toString() {
return "Degree [ " + degreeId + " - " + degreeEn + "/" + degreeFr + " ]";
}
}
package pack.datas.controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class DaoController {
#GetMapping("/")
#ResponseBody
#Transactional(readOnly = true)
String home() {
return "<h1>Test Program</h1>";
}
}
The pom.xml :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pack</groupId>
<artifactId>candidates-recruitment</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>candidates-recruitment</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.surefire/surefire-api -->
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-api</artifactId>
<version>2.19.1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
The application.yml :
# DATASOURCE (DataSourceProperties)
spring:
datasource:
url: jdbc:postgresql://localhost:5432/recruitments_db
username: postgresql
password: postgresql
driver-class-name: org.postgresql.Driver
# HIBERNATE (HibernateProperties)
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
show_sql: true
hbm2ddl.auto: create
#SECURITY (SecuriyProperties)
security:
user:
name: TestU
password: Test1
Please, I need your help !
Seems like you used #Id annotation from the wrong package in your Degree class. Change your import from org.springframework.data.annotation.Id to javax.persistence.Id. That should help with the exception you're getting.
use
javax.persistence.Id
instead of
org.springframework.data.annotation.Id
will solve the problem
I encountered the same problem today.After some debugging,got to know that I annotated one of the fields in my model class with #GeneratedValue(strategy = GenerationType.AUTO) but didn't add the #Id annotation to that field.Adding one resolved it.
Hibernate jar was corrupted in local repository of maven,it was taking corrupted library every time, after deleting local maven repository issue resolved
C:\Users\user.m2\repository
This error might be related to wrong database configuration in your project.
In your application.yml or application.properties file, you would be given wrong db name in "spring.datasource.url" .
A bit late to the party but I ran into the same problem and this is what fixed it:
diff --git a/pom.xml b/pom.xml
index 3a65505..96e5640 100644
--- a/pom.xml
+++ b/pom.xml
## -19,7 +19,7 ##
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
- <version>2.0.6.RELEASE</version>
+ <version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
Encountered the same problem after importing my project to IntelliJ IDE. Turned out it was easier than I thought I went to pom.xml and right-clicked on "+ Add as a Maven project". This solved the problem.