Wildfly Swarm EntityManager is null - java

I have a microservice which is a scheduler. I get a timing job via REST json.
I followed some tutorials on how to add the persistence.xml but it doesn't seem to work. I don't get any failure messages but the NullpointerException from the EntityManager.
It doesn't create the tables etc. so i think there is a problem with adding the persistence.xml too?
There is no problem in connecting to the datasource. i tested it and it seems to work properly.
SchedulerMain:
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.datasources.DatasourceArchive;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
public class SchedulerMain {
public static void main(String[] args) {
try {
Container container = new Container();
container.start();
container.deploy(Swarm.artifact("mysql:mysql-connector-java", "mysql"));
deployApp(container);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void deployApp(Container container) throws Exception {
JAXRSArchive app = ShrinkWrap.create(JAXRSArchive.class);
app.as(DatasourceArchive.class).dataSource("Scheduler", (ds) -> {
ds.connectionUrl("jdbc:mysql://localhost:3306/scheduler");
ds.driverName("mysql");
ds.userName("root");
ds.password("");
});
app.addAsWebInfResource(new ClassLoaderAsset("META-INF/persistence.xml", SchedulerMain.class.getClassLoader()),
"classes/META-INF/persistence.xml");
app.addAsLibrary(container.createDefaultDeployment());
app.addAllDependencies();
container.deploy(app);
}
}
ScheduleRESTResource:
#ApplicationScoped
#Path("/schedule")
public class ScheduleRESTResource {
#Inject
private SchedulerController schedulerController;
#Inject
private ScheduleBean scheduleBean;
#POST
#Path("/job")
#Consumes(MediaType.APPLICATION_JSON)
public void schedule(MySchedule schedule) throws IOException {
List<MySchedule> schedules = scheduleBean.getAllSchedules();
System.out.println(schedules.toString());
schedulerController.buildSchedule(schedule);
}
}
ScheduleBean:
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import de.fszm.scheduler.entities.MySchedule;
#Stateless
public class ScheduleBean {
#PersistenceContext(unitName = "Scheduler")
private EntityManager em;
public List<MySchedule> getAllSchedules() {
System.out.println("getAllSchedules");
List<MySchedule> schedules = new ArrayList<>();
if (em != null) {
schedules = em.createNamedQuery("Schedule.getAllSchedules", MySchedule.class).getResultList();
} else {
System.out.println("em is null");
}
return schedules;
}
}
persistence.xml:
<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="Scheduler" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/Scheduler</jta-data-source>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/scheduler"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="drop-and-create"/>
</properties>
</persistence-unit>
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>...</groupId>
<artifactId>scheduler</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>scheduler</name>
<packaging>jar</packaging>
<properties>
<version.swarm>1.0.0.Beta6</version.swarm>
<version.mysql>5.1.6</version.mysql>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>bom</artifactId>
<version>${version.swarm}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>undertow</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>ejb</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>jaxrs-weld</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>datasources</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${version.mysql}</version>
</dependency>
<!-- <dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>wildfly-swarm-ejb</artifactId>
<version>1.0.0.Alpha5</version>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.wildfly.swarm</groupId>
<artifactId>wildfly-swarm-plugin</artifactId>
<version>${version.swarm}</version>
<configuration>
</configuration>
<executions>
<execution>
<id>package</id>
<goals>
<goal>package</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

Related

Whitelabel Error Page This application has no explicit mapping for /error

I have problem with my application. I added uploading image page but i get problem.
enter image description here
Before my project work corretly. I can login in test1 be user and test3. Admin can log test2 and test3, but when i add uploadImage and i wanna log be Admin i get whitelabel, if i change this for user i get this same problem. I think this should be problem with mapping or scaning, my structure maybe is not correctly but idk because i dont have enough experience. Lower i add my code, if someone need more code, ask.
My uploadImage:
package com.example.imageUploader.gui;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.Route;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.imageUploader.ImageUploader;
import org.springframework.web.bind.annotation.GetMapping;
import java.awt.*;
// problem moze byc z mapowaniem albo zaleznosciami miedzy folderami ze ten jest za wysoko
#Route("uploadImage")
public class UploadGui extends VerticalLayout
{
private ImageUploader imageUploader;
#Autowired
public UploadGui(ImageUploader imageUploader)
{
this.imageUploader = imageUploader;
TextField textField = new TextField();
Button button = new Button("upload");
button.addClickListener(clickEvent -> imageUploader.uploadFile(textField.getValue()));
add(textField);
add(button);
}
}
My run:
package com.example.imageUploader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
#SpringBootApplication
//#ComponentScan(basePackages = "com.example.imageUploader.gui.UploadGui")
public class ImageUploaderApplication {
public static void main(String[] args) {
SpringApplication.run(ImageUploaderApplication.class, args);
}
}
My logging:
package com.example.imageUploader;
import com.example.imageUploader.model.AppUser;
import com.example.imageUploader.repo.AppUserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Collections;
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
private UserDetailsServiceImpl userDetailsService;
private AppUserRepo appUserRepo;
#Autowired
public WebSecurityConfig(UserDetailsServiceImpl userDetailsService, AppUserRepo appUserRepo) {
this.userDetailsService = userDetailsService;
this.appUserRepo = appUserRepo;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.antMatchers("/test1").hasRole("USER")
.antMatchers("/test2").hasRole("ADMIN")
.antMatchers("/uploadImage").hasRole("ADMIN")
.and()
.formLogin().permitAll();
}
#Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
#EventListener(ApplicationReadyEvent.class)
public void get()
{
AppUser appUserUser = new AppUser("User", passwordEncoder().encode("haslo123"), "ROLE_USER");
AppUser appUserAdmin = new AppUser("Admin", passwordEncoder().encode("haslo123"), "ROLE_ADMIN");
appUserRepo.save(appUserUser);
appUserRepo.save(appUserAdmin);
}
}
My 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.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>imageUploader</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>imageUploader</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<vaadin.version>23.1.4</vaadin.version>
</properties>
<dependencies>
<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>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.cloudinary</groupId>
<artifactId>cloudinary-http44</artifactId>
<version>1.22.1</version>
</dependency>
<dependency>
<groupId>com.cloudinary</groupId>
<artifactId>cloudinary-taglib</artifactId>
<version>1.0.14</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>${vaadin.version}</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>
</plugins>
</build>
<profiles>
<profile>
<id>production</id>
<build>
<plugins>
<plugin>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-maven-plugin</artifactId>
<version>${vaadin.version}</version>
<executions>
<execution>
<id>frontend</id>
<phase>compile</phase>
<goals>
<goal>prepare-frontend</goal>
<goal>build-frontend</goal>
</goals>
<configuration>
<productionMode>true</productionMode>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
Screen of my structure:
enter image description here
Ok, problem solved. I put this part of my pom.xml in the comment and resolve problem.
<profiles>
<profile>
<id>production</id>
<build>
<plugins>
<plugin>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-maven-plugin</artifactId>
<version>${vaadin.version}</version>
<executions>
<execution>
<id>frontend</id>
<phase>compile</phase>
<goals>
<goal>prepare-frontend</goal>
<goal>build-frontend</goal>
</goals>
<configuration>
<productionMode>true</productionMode>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>

Hibernate PropertyAccessException. Spring dependencies problem

My application originally used only Hibernate and everything worked fine, but with Spring i'm getting an exception. It feels like Spring causes different behavior for Hibernate.
So with Spring & Hibernate i get this exception trace:
Stack trace photo_1
Stack trace photo_2
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/IndexingAndSearching?
serverTimezone=UTC</property>
<property name="connection.CharSet">utf8</property>
<property name="connection.characterEncoding">utf8</property>
<property name="connection.useUnicode">true</property>
<property name="connection.username">test</property>
<property name="connection.password">test</property>
<property name="connection.pool_size">20</property>
<property name="dialect">org.hibernate.dialect.MySQL57Dialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">validate</property>
</session-factory>
</hibernate-configuration>
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>IndexingAndSearching</groupId>
<artifactId>IndexingAndSearching</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Lucene -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>9.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>8.11.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>9.0.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.7.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version>
</dependency>
<!-- Logger -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
<!-- JUnit -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
All of my DAO methods for mysql are written with sessionFactory
Links - my only table
#Entity(name = "links")
#Table(name = "links")
#DynamicInsert // To set initial value of fields, otherwise doesn't work
public class Links implements Serializable {
#Id
private String link;
#Enumerated
#Column(columnDefinition = "smallint")
private Status status;
#Version
private int version;
private int depth;
private long owner;
public Links() {
} // hibernate requirement
public Links(String link, Status status, int depth) throws URISyntaxException {
assert depth >= 0;
assert !LinkParser.isBlank(link);
this.link = link;
this.status = status;
this.depth = depth;
this.owner = 0;
}
public String getLink() {
return link;
}
private void setLink(String link) {
this.link = link;
}
public int getVersion() {
return version;
}
private void setVersion(int version) {
this.version = version;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public int getDepth() {
return depth;
}
private void setDepth(int depth) {
this.depth = depth;
}
public long getOwner() {
return owner;
}
public void setOwner(long owner) {
assert owner >= 0;
this.owner = owner;
}
application.properties
server.port=8080
server.servlet.context-path=/webcrawler
Only difference is when i start application with Spring, i dont get these exceptions when i dont use Spring.
I think the issue is from the fact that you setter is private and should be public
private void setLink(String link) {
this.link = link;
}
Should be
public void setLink(String link) {
this.link = link;
}
Same for setVersion and setDepth
I found out, I commented these maven dependencies
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-devtools</artifactId>-->
<!-- <scope>runtime</scope>-->
<!-- <optional>true</optional>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-test</artifactId>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
And everything started working... I guess devtools are the reason, dont want to check, I tried so many other stuff, and this is the reason...

NodeEntity attributes are NULL after transaction closed when using AspectJ

I've got a strange problem when using AspectJ, Neo4j NodeEntities and transactions.
I'm developing a spring application and using spring-data-neo4j with aspectj weaving. The problem is, that my fetched entities are empty outside of the transaction. Without AspectJ everything works as expected.
Here is a full test-case with maven:
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>org.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<neo4j.version>2.1.7</neo4j.version>
<spring-data-commons.version>1.10.0.RELEASE</spring-data-commons.version>
<spring-data-neo4j.version>3.3.0.RELEASE</spring-data-neo4j.version>
</properties>
<dependencies>
<!-- spring dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${spring-data-commons.version}</version>
</dependency>
<!-- spring + neo4j dependencies -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-tx</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-aspects</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<!-- for aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
<optional>true</optional>
<scope>provided</scope>
</dependency>
<!-- for testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-kernel</artifactId>
<version>${neo4j.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>aspects</id>
<build>
<plugins>
<!-- disable default compiler -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
<!-- enable aspectj compiler -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.8.5</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<outxml>true</outxml>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
<aspectLibrary>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
<complianceLevel>${java.version}</complianceLevel>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<repositories>
<repository>
<id>spring-libs-milestone</id>
<name>Spring Milestone</name>
<url>https://repo.spring.io/libs-milestone</url>
</repository>
</repositories>
</project>
demo/DemoNode.java
package demo;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
#NodeEntity
public class DemoNode {
#GraphId
private Long id;
#Indexed(unique = true)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
demo/DemoRepository.java
package demo;
import org.springframework.data.neo4j.repository.GraphRepository;
public interface DemoRepository extends GraphRepository<DemoNode> {
public DemoNode findByName(String name);
}
demo/DemoApplicationTests.java
package demo;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.test.TestGraphDatabaseFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.aspects.config.Neo4jAspectConfiguration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.support.node.Neo4jHelper;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class DemoApplicationTests {
#Configuration
#ComponentScan("demo")
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = "demo")
public static class DemoConfiguration extends Neo4jAspectConfiguration {
public DemoConfiguration() {
setBasePackage("demo");
}
#Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
return new TestGraphDatabaseFactory().newImpermanentDatabase();
}
}
#Autowired
private GraphDatabaseService graphDbService;
#Autowired
private DemoRepository demoRepo;
#Before
public void resetDb() {
Neo4jHelper.cleanDb(graphDbService);
}
// NOT successful
#Test
public void testNeo4jTransaction() {
DemoNode node;
final String name = "demo";
try (Transaction tx = graphDbService.beginTx()) {
node = new DemoNode();
node.setName(name);
node = demoRepo.save(node);
tx.success();
}
assertEquals(name, node.getName());
try (Transaction tx = graphDbService.beginTx()) {
node = demoRepo.findByName(name);
tx.success();
}
assertEquals(name, node.getName()); // expected:<demo> but was:<null>
}
// successful
#Test
public void testNeo4jWithGetTransaction() {
DemoNode node;
final String name = "demo";
try (Transaction tx = graphDbService.beginTx()) {
node = new DemoNode();
node.setName(name);
node = demoRepo.save(node);
tx.success();
}
assertEquals(name, node.getName());
try (Transaction tx = graphDbService.beginTx()) {
node = demoRepo.findByName(name);
tx.success();
}
try (Transaction tx = graphDbService.beginTx()) {
assertEquals(name, node.getName());
}
}
}
When you test this with mvn test everything is fine. But when using aspectj (mvn test -Paspects) it will fail:
DemoApplicationTests.testNeo4jNativeTransaction:64 expected:<demo> but was:<null>
What I found out when debugging this: Inside the transaction with AspectJ I could retrieve the name with the getter. BUT: All properties are always null. So my guess is: AspectJ weaving stores the values somewhere else and overrides the setter/getter for this. The new getter requires an active transaction, so outside of the transaction it will not work/will use the default getter that doesn't work with the null properties.
When I'm increasing the debug level I could see some message regarding this:
DEBUG o.s.d.n.f.DetachedEntityState - Outside of transaction, GET value from field class java.lang.String name rel: false idx: true
Am I doing something wrong? Do I need to create a clone and return this? Imho this would be an ugly way ...
Thanks in advance! I'm already searched and tried multiple hours but couldn't find any solution and any other problems here on stackoverflow or somewhere else in the internet. Maybe it's a bug ... maybe expected behaviour or maybe I'm doing some wrong ... I don't know.
UPDATE
I added a second test that works. It has a transaction around the getter. So when the getter is called in a transaction everything is fine. But I think this is a curious behaviour. Outside of the transaction the entity should be detached, but usable.

No Persistence provider for EntityManager named persistenceUnit

I'm working on REST server and learning EJB\hibernate at the same time. When service call DAO I faced with an issue that it can not find my persistence unit.
#Stateless
public class HotelDAO {
#PersistenceContext(unitName = Constants.PERSISTENCE_UNIT)
private EntityManager em;
public List<HotelsEntity> getAll() {
// TODO complete me
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<HotelsEntity> criteria = builder.createQuery(HotelsEntity.class);
Root<HotelsEntity> root = criteria.from(HotelsEntity.class);
criteria.select(root);
TypedQuery<HotelsEntity> resultQuery = em.createQuery(criteria);
return resultQuery.getResultList();
}
}
In this case I get "Unable to retrieve EntityManagerFactory for unitName persistenceUnit"
Then I try this:
#Stateless
public class HotelDAO {
public List<HotelsEntity> getAll() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit");
EntityManager em = emf.createEntityManager();
// TODO complete me
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<HotelsEntity> criteria = builder.createQuery(HotelsEntity.class);
Root<HotelsEntity> root = criteria.from(HotelsEntity.class);
criteria.select(root);
TypedQuery<HotelsEntity> resultQuery = em.createQuery(criteria);
return resultQuery.getResultList();
}
}
In this case I get "No Persistence provider for EntityManager named persistenceUnit".
I checl similar issues at the stackoverflow:
persitence.xml under META-INF
DAO is injected into EJB
provider is mentioned in persistence.xml
I don't use Spring
Do you have any gueses?
<?xml version="1.0" encoding="UTF-8"?>
<persistence-unit name="persistenceUnit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/HospitalityDataSource</jta-data-source>
<class>com.example.model.AmmenitiesEntity</class>
<class>com.example.model.HotelPropertyEntity</class>
<class>com.example.model.HotelsEntity</class>
<class>com.example.model.InventoriesEntity</class>
<class>com.example.model.ReservationEntity</class>
<class>com.example.model.RoomEntity</class>
<class>com.example.model.RoomPropertyEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="dbroot"/>
<property name="hibernate.connection.password" value="password"/>
</properties>
</persistence-unit>
pom.xml
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>annotations-api</artifactId>
<version>6.0.29</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.ejb</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
If I'm not wrong, I think persistence.xml must be in src/main/resources/META-INF/persistence.xml

No Persistence provider for EntityManager named cache

Message.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name="MESSAGES")
#Cache(region = "messages", usage = CacheConcurrencyStrategy.READ_WRITE)
public class Message {
Message(){
}
Message(String message){
message_text=message;
}
#Id #GeneratedValue
#Column(name="MESSAGE_ID")
public Long id;
#Column(name="MESSAGE_TEXT")
public String message_text;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage_text() {
return message_text;
}
public void setMessage_text(String message_text) {
this.message_text = message_text;
}
}
Ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
<cache name="messages" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />
</ehcache>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="annotation">
<properties>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#ebiz-dev-db-esb:1521:esbd"/>
<property name="hibernate.connection.username" value="CUST_INFO"/>
<property name="hibernate.connection.password" value="POUND987"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9Dialect"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
<property name="show_sql" value="true"/>
<property name="format_sql" value="true"/>
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.EhCacheProvider" />
<property name="hibernate.cache.provider_configuration_file_resource_path" value="ehcache.xml" />
</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>HibernateWithAnnotation</groupId>
<artifactId>HibernateWithAnnotation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>HibernateWithAnnotation</name>
<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.5</version>
</dependency>
</dependencies>
</project>
TestAnnotation class
package com.annotation;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class TestAnnotation {
public static void main(String args[]){
EntityManagerFactory factory=Persistence.createEntityManagerFactory("annotation");
EntityManager manager=factory.createEntityManager();
EntityTransaction transaction=manager.getTransaction();
transaction.begin();
manager.persist(new Message("My Entity Test One More Example New"));
transaction.commit();
System.out.println("First time calling Message Object");
getMessage(manager,23);
System.out.println("Second time calling Message Object");
getMessage(manager,23);
factory.close();
}
public static void getMessage(EntityManager manager,long id){
EntityTransaction transaction1=manager.getTransaction();
transaction1.begin();
Query q=manager.createQuery("from Message m where m.id="+id);
Message m=(Message)q.getSingleResult();
System.out.println(m.getMessage_text());
transaction1.commit();
}
}
My problem is: When I run this code from TestAnnotation class via main method I get the following error:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named annotation
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at com.annotation.TestAnnotation.main(TestAnnotation.java:10)
Your persistence-unit is incomplete. See the documentation.
Add <class>com.annotation.TestAnnotation</class> to your persistence-unit node in your persistence.xml file before the properties node.
You likely also need transaction-type="RESOURCE_LOCAL" on you persistence-unit node.
For example, my working version uses:
pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.4-Final</version>
<scope>runtime</scope>
</dependency>
persistenct.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="MyPU" transaction-type="RESOURCE_LOCAL">
<class>com.myentities.MyEntity</class>
<properties>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<!-- These lines can be used for debugging -->
<!--<property name="show_sql" value="true"/>-->
<!--<property name="format_sql" value="true"/>-->
</properties>
</persistence-unit>
</persistence>
My DAO class:
private EntityManager m_entityManagerFactory;
// initializer (this is costly, do only 1x on post construct)
m_entityManager = createEntityManagerFactory( jdbcDriverName, jdbcURL, dbUserName, dbPassword );
// when needed (less costly, can do 1x or whenever you need the entity manager)
EntityManager entityManager = m_entityManagerFactory.createEntityManager();
private EntityManagerFactory createEntityManagerFactory (
#NotNull final String jdbcDriverName,
#NotNull final String jdbcURL,
#NotNull final String dbUserName,
#NotNull final String dbPassword )
{
final Properties properties = new Properties();
properties.put( "hibernate.connection.driver_class", jdbcDriverName );
properties.put( "hibernate.connection.url", jdbcURL );
properties.put( "hibernate.connection.username", dbUserName );
properties.put( "hibernate.connection.password", dbPassword );
return Persistence.createEntityManagerFactory( "AlertProcessorPU", properties );
}

Categories

Resources