I am learning JPA with sample project. Whenever I execute the program, it returns null. I checked follow
JPA - createEntityManagerFactory returns Null ,But,this is not helping. please help me. i have been stuck two days. I dont know where i do mistakes .
Following Exception is always happening,
1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl#482e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions#967906] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions#18dfcc1]
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:84)
at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:67)
at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.handleEntry(ClassFileArchiveEntryHandler.java:53)
at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:147)
at org.hibernate.boot.archive.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:47)
at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordinateScan(ScanningCoordinator.java:76)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:98)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:242)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:175)
at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:76)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:171)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:119)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:61)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:50)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at com.test.jpa.App.main(App.java:19)
Main class
public class App
{
public static void main( String[] args )
{
System.out.println( "I am going to connect" );
BasicConfigurator.configure();
Logger.getLogger("org").setLevel(Level.ALL);
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("boom");
if(entityManagerFactory !=null ) {
System.out.println( "lalala" );
}else {
System.out.println( "nullllllllllllll" );
}
}
}
This is Mapping class,
package com.test.jpa;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "client")
public class User {
#Column(name = "name")
private String name = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Column(name = "age")
private int age = 0;
#Id
#Column(name = "No")
private int No = 0;
public int getNo() {
return No;
}
public void setNo(int no) {
No = no;
}
}
pom file
<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.test</groupId>
<artifactId>jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>jpa</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.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.11.Final</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<optimize>true</optimize>
<debug>true</debug>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<dependencySets>
<dependencySet>
<includes>
<include>*:jar:*</include>
</includes>
<excludes>
<exclude>*:sources</exclude>
<exclude>*:javadoc</exclude>
</excludes>
</dependencySet>
</dependencySets>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.test.jpa.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="boom" >
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.test.jpa.User</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:6767/User"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="atis"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.autocommit" value="false"/>
<property name="hibernate.connection.provider_disables_autocommit" value="true"/>
</properties>
</persistence-unit>
</persistence>
I created database with name User, table is "client" , cloumn are "No","age"-integer datatype, "name"-string datatype
update:
I tested with junit tool with follow class.
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PersonTest {
private EntityManagerFactory emf;
private EntityManager em;
#Before
public void initEmfAndEm() {
BasicConfigurator.configure();
Logger.getLogger("org").setLevel(Level.ALL);
emf = Persistence.createEntityManagerFactory("boom");
if(emf !=null)
System.out.println("wooooooooooooooooooooo ");
em = emf.createEntityManager();
}
#After
public void cleanup() {
em.close();
}
#Test
public void emptyTest() {
}
}
When it gets executed, it is not throws null pointer exception. it prints like follow, then it passes to sucessive execution.
844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl#45312be2] into BootstrapContext; was [null]
844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions#7fb95505] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions#58be6e8]
903 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl - Injecting JPA temp ClassLoader [null] into BootstrapContext; was [null]
903 [main] DEBUG org.hibernate.boot.internal.ClassLoaderAccessImpl - ClassLoaderAccessImpl#injectTempClassLoader(null) [was null]
But when execute using well packaged jar in command line,exeception is thrown
1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl#482e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions#967906] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions#18dfcc1]
Exception in thread "main" java.lang.NullPointerException
thanks
I fixed problem .It was dependency problem. In pom file, After i added following
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.12.Final</version>
</dependency>
and removed following dependency
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.11.Final</version>
</dependency>
hibernate-entitymanager will add all necessary dependency.
Packing problem during build time
You configuration looks right. Probably it's a packing problem. Try build and run you project with the following commands and it will work:
mvn clean compile assembly:single
java -jar target/jpa-0.0.1-SNAPSHOT-jar-with-dependencies.jar
Take a look this answer to see more about how to create a jar with dependencies.
Maven - Build with Dependencies
More details for the sake of correctness:
org.hibernate:hibernate-core is the right dependecy to be used.
org.hibernate:hibernate-entitymanager is deprecated and actually only points to hibernate-core.
Reference inside jar:
Hibernate's JPA support has been merged into the hibernate-core
module, making this hibernate-entitymanager module obsolete. This
module will be removed in Hibernate ORM 6.0. It is only kept here for
various consumers that expect a static set of artifact names across a
number of Hibernate releases. See
https://hibernate.atlassian.net/browse/HHH-10823
Related
So I'm developing an API and I'm trying to connect to a local docker instance of DB2 from java using JPA entity manager. After running Apache Maven and getting build success, I try a GET request from Postman to test an endpoint and get a list of all users from DB2. I'm receiving the below error saying that entity manager is null. I've tried researching online and can't seem to find the solution.
The Dao class is virtually unchanged from a previous iteration that used Derby instead of DB2 and it worked fine.
I was wanting to know where I've gone wrong, what needs changing, and if anything is not needed. Provided below is the xml files and the DAO java class containing the entity manager. All properties for DB2 is correct as they're unchanged from a successful connection I was able to do from Eclipse's Database Development. The driver used then was db2jcc4 which I think is different to the driver said to use for the maven dependency so not sure if that's an issue.
Postman:
Error 500: java.lang.NullPointerException: Cannot invoke
"javax.persistence.EntityManager.createNamedQuery(String, java.lang.Class)" because
"this.em" is null
Maven:
[INFO] [ERROR ] CWWJP0015E: An error occurred in the org.eclipse.persistence.jpa.PersistenceProvider persistence provider when it attempted to create the container entity manager factory for the jpa-unit persistence unit. The following error occurred: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.7.9.v20210604-2c549e2208): org.eclipse.persistence.exceptions.EntityManagerSetupException
[INFO] Exception Description: Predeployment of PersistenceUnit [jpa-unit] failed.
[INFO] Internal Exception: javax.persistence.PersistenceException: CWWJP0013E: The server cannot locate the java:comp/DefaultDataSource data source for the jpa-unit persistence unit because it has encountered the following exception: javax.naming.NameNotFoundException: javax.naming.NameNotFoundException: java:comp/DefaultDataSource.
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.obdoblock</groupId>
<artifactId>hyperledger-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- Liberty configuration -->
<liberty.var.default.http.port>3500</liberty.var.default.http.port>
<liberty.var.default.https.port>9443</liberty.var.default.https.port>
<liberty.var.app.context.root>api</liberty.var.app.context.root>
<!-- TestDB Configuration -->
<version.ibm.db2>11.5.6.0</version.ibm.db2>
</properties>
<dependencies>
<!-- Provided dependencies -->
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>8.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.microprofile</groupId>
<artifactId>microprofile</artifactId>
<version>3.3</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
<!-- For tests -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.3.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.3.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>1.0.7</version>
<scope>test</scope>
</dependency>
<!-- DB2 connector -->
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>jcc</artifactId>
<version>11.5.6.0</version>
</dependency>
<!-- Hyperledger Fabric Gateway for Blockchain -->
<dependency>
<groupId>org.hyperledger.fabric</groupId>
<artifactId>fabric-gateway-java</artifactId>
<version>2.2.0</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- Enable liberty-maven plugin -->
<plugin>
<groupId>io.openliberty.tools</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>3.3.4</version>
<configuration>
<copyDependencies>
<location>${project.build.directory}/liberty/wlp/usr/shared/resources</location>
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>jcc</artifactId>
<version>11.5.6.0</version>
</dependency>
</copyDependencies>
</configuration>
</plugin>
<!-- Plugin to run functional tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<systemPropertyVariables>
<http.port>${liberty.var.default.http.port}</http.port>
<context.root>${liberty.var.app.context.root}</context.root>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
</plugin>
<!-- Plugin to run unit tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
</project>
server.xml
<server description="Obdoblock REST Server">
<featureManager>
<feature>jaxrs-2.1</feature>
<feature>openapi-3.1</feature>
<feature>jpa-2.2</feature>
<feature>cdi-2.0</feature>
</featureManager>
<httpEndpoint
httpPort="${default.http.port}"
httpsPort="${default.https.port}"
id="defaultHttpEndpoint"
host="*"
/>
<webApplication
location="hyperledger-api.war"
contextRoot="${app.context.root}"
/>
<!-- DB2 Library Configuration -->
<library id="DB2JCCLib">
<fileset dir="${shared.resource.dir}" includes="*.jar" />
</library>
<dataSource jndiName="jdbc/db2">
<jdbcDriver libraryRef="jdbcLib"/>
<properties
databaseName="testdb"
serverName="localhost"
portNumber="50000"
user="****" password="****"
/>
</dataSource>
</server>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- TODO: This will have to be configured by ENV as well -->
<!-- https://www.eclipse.org/eclipselink/documentation/2.5/jpa/extensions/p_ddl_generation.htm -->
<persistence version="2.2"
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_2.xsd">
<persistence-unit name="jpa-unit" transaction-type="JTA">
<properties>
<!-- Connection Specific -->
<property name="hibernate.dialect" value="org.hibernate.dialect.DB2Dialect"/>
<property name="javax.persistence.jdbc.driver" value="com.ibm.db2.jcc.DB2Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:db2://localhost:50000/testdb" />
<property name="javax.persistence.jdbc.user" value="****" />
<property name="javax.persistence.jdbc.password" value="****" />
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
</persistence>
UserDao.java
package dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.enterprise.context.RequestScoped;
import models.*;
#RequestScoped
public class UserDao {
#PersistenceContext(name = "jpa-unit")
private EntityManager em;
public void createUser(Users user){
em.persist(user);
}
public Users readUser(int userId){
return em.find(Users.class, userId);
}
public List<Users> readAllUsers(){
return em.createNamedQuery("Users.findAll", Users.class).getResultList();
}
public void updateUser(Users user){
em.merge(user);
}
public void deleteUser(Users userId){
em.remove(userId);
}
public List<Users> findUser(String email){
return em.createNamedQuery("Users.findUser", Users.class)
.setParameter("email", email)
.getResultList();
}
public void createHistory(History hist){
em.persist(hist);
}
//wait this doesnt do anything?
public Users readHistory(int id){
return em.find(Users.class, id);
}
public List<History> readAllHistory(){
return em.createNamedQuery("History.findAll", History.class).getResultList();
}
}
Versions:
Docker: 20.10.8, build 3967b7d
DB2: ibm/db2 docker image version 11.5.6
Maven: 3.8.3
Java: JDK 14.0.2
If needing any more details, I'm happy to provide them.
Thanks, Dylan
Your persistence.xml is incorrect. It should point to datasource configured in the server.xml, not specify driver properties.
Like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
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_2.xsd">
<persistence-unit name="jpa-unit" transaction-type="JTA">
<jta-data-source>jdbc/guestbookDS</jta-data-source>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create" />
<property name="javax.persistence.schema-generation.create-database-schemas" value="true" />
<property name="javax.persistence.schema-generation.scripts.action" value="create" />
<property name="javax.persistence.schema-generation.scripts.create-target" value="create.ddl"/>
<!--
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="both" />
-->
</properties>
</persistence-unit>
</persistence>
You can check this very simple Liberty project which uses JPA and database here https://github.com/stocktrader-ops/db-sat-demo (it is using PostgreSQL instead of DB2, but you should just use your datasource setup)
i'm facing a problem with connection to MySQL database by java. I've tried to change versions in pom.xml of hibernate-core/hibernate-entitymanager/hibernate-jpa and nothing worked.
It seems that it is a problem with hibernate-jpa duplication or it not working with mysql-connecot. After 2 hours of trying all these different versions i've decided to ask for help.
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>Pracownia</groupId>
<artifactId>PracowniaMain</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<resources>
<resource>
<directory>src</directory>
<includes>
<include>META-INF/persistence.xml</include>
</includes>
</resource>
</resources>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<attach>false</attach>
<appendAssemblyId>false</appendAssemblyId>
<archive>
<manifest>
<mainClass>
hibernate.Manager
</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Hibernate resources -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.2.Final</version>
<classifier>tests</classifier>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<!-- Java Bind -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
</project>
persistence.xml:
<!--<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">-->
<persistence 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="hibernate-dynamic" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!--<class>org.halyph.sessiondemo.Event</class>-->
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/phpmyadmin?useSSL=false" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.connection.driver_class" value ="com.mysql.cj.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.format_sql" value="false"/>
</properties>
</persistence-unit>
</persistence>
Then after running this:
package hibernate;
import hibernate.model.artysci;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;
class Manager {
public static void main(String[] args) {
System.out.println("Start");
EntityManager entityManager = null;
EntityManagerFactory entityManagerFactory = null;
System.out.println("Start2");
try {
System.out.println("Start3");
//taka nazwa jak w persistence.xml
entityManagerFactory = Persistence.createEntityManagerFactory("hibernate-dynamic");
//utworz entityManagera
System.out.println("Start4");
entityManager = entityManagerFactory.createEntityManager();
//rozpocznij transakcje
entityManager.getTransaction().begin();
//System.out.println("dis");
/*
Employee emp = new Employee();
emp.setFirstName("Jan");
emp.setLastName("Polak");
emp.setSalary(100);
emp.setPesel(100);
entityManager.persist(emp);
Employee employee = entityManager.find(Employee.class, emp.getId());
entityManager.remove(emp);
System.out.println("Employee " + employee.getId() + " " + employee.getFirstName() + employee.getLastName());
*/
//zakoncz transakcje
entityManager.getTransaction().commit();
System.out.println("Done");
entityManager.close();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
} finally {
entityManagerFactory.close();
}
}
}
Console:
Start
Start2
Start3
2021-01-06 18:52:56 DEBUG logging:38 - Logging Provider: org.jboss.logging.Log4jLoggerProvider
2021-01-06 18:52:56 INFO LogHelper:31 - HHH000204: Processing PersistenceUnitInfo [
name: hibernate-dynamic
...]
2021-01-06 18:52:57 INFO Version:37 - HHH000412: Hibernate Core {5.2.0.Final}
2021-01-06 18:52:57 INFO Environment:213 - HHH000206: hibernate.properties not found
2021-01-06 18:52:57 INFO Environment:318 - HHH000021: Bytecode provider name : javassist
2021-01-06 18:52:57 INFO Version:66 - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2021-01-06 18:52:57 WARN connections:71 - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
2021-01-06 18:52:57 INFO connections:127 - HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost/phpmyadmin?useSSL=false]
2021-01-06 18:52:57 INFO connections:136 - HHH10001001: Connection properties: {user=root}
2021-01-06 18:52:57 INFO connections:141 - HHH10001003: Autocommit mode: false
2021-01-06 18:52:57 INFO DriverManagerConnectionProviderImpl:39 - HHH000115: Hibernate connection pool size: 20 (min=1)
2021-01-06 18:52:57 INFO Dialect:152 - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Initial SessionFactory creation failed.java.lang.NoSuchMethodError: javax/persistence/Table.indexes()[Ljavax/persistence/Index; (loaded from file:/C:/Users/xxx/Desktop/PROJEKT%202/lib/javax.persistence.jar by sun.misc.Launcher$AppClassLoader#102dc1cf) called from class org.hibernate.cfg.annotations.EntityBinder (loaded from file:/C:/Users/xxx/.m2/repository/org/hibernate/hibernate-core/5.2.0.Final/hibernate-core-5.2.0.Final.jar by sun.misc.Launcher$AppClassLoader#102dc1cf).
Exception in thread "main" java.lang.NullPointerException
at hibernate.Manager.main(Manager.java:59)
Process finished with exit code -1
Thanks for help!
The problem is related to your dependencies, some of them in a transitive way load different versions of JPA so this produces the error.
In the case of your pom, you have 3 times the same dependency:
hibernate-entity-manager (in a transitive way load hibernate-jpa-2.0-api:1.0.0.Final)
hibernate-core (in a transitive way load hibernate-jpa-2.0-api:1.0.0.Final)
hibernate-jpa-2.0-api
All of them import "hibernate-jpa-2.0-api" but with a different version. I recommend removing hibernate-jpa-2.0-api
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
Another option is to exclude the dependency for the other dependencies.
A good plugin to check all the possible conflicts in your is Enforce
I am trying to create custom loadtime annotations with AspectJ, Open JDK11 without Spring Context. It works fine within a module and annotations are weaving at class load time and aspects are executing at runtime. No issues, But when aspectJ implemented module added as a dependency on another module with spark routes. AspectJ and annotations are not processing. Am I missing any configuration?
Parent POM:
<?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>de.scrum-master</groupId>
<artifactId>aspectj-ltw-test-multi-module</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.source-target.version>11</java.source-target.version>
<aspectj.version>1.9.4</aspectj.version>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java.source-target.version}</source>
<target>${java.source-target.version}</target>
<!-- IMPORTANT -->
<useIncrementalCompilation>false</useIncrementalCompilation>
</configuration>
</plugin>
<plugin>
<groupId>com.nickwongdev</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.12.1</version>
<configuration>
<!--<showWeaveInfo>true</showWeaveInfo>-->
<source>${java.source-target.version}</source>
<target>${java.source-target.version}</target>
<Xlint>ignore</Xlint>
<complianceLevel>${java.source-target.version}</complianceLevel>
<encoding>${project.build.sourceEncoding}</encoding>
<!--<verbose>true</verbose>-->
<!--<warn>constructorName,packageDefaultMethod,deprecation,maskedCatchBlocks,unusedLocals,unusedArguments,unusedImport</warn>-->
</configuration>
<executions>
<execution>
<!-- IMPORTANT -->
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>de.scrum-master</groupId>
<artifactId>aspect</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>aspect</module>
<module>application</module>
</modules>
</project>
Aspect module:
<?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>de.scrum-master</groupId>
<artifactId>aspectj-ltw-test-multi-module</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>de.scrum-master</groupId>
<artifactId>aspect</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>com.nickwongdev</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
</dependencies>
</project>
<aspectj>
<aspects>
<aspect name="de.scrum_master.aspect.CounterAspect"/>
</aspects>
<weaver options="-verbose">
<!-- weave anything -->
<include within="*"/>
</weaver>
</aspectj>
package de.scrum_master.aspect;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
#Documented
#Inherited
#Target(METHOD)
#Retention(RUNTIME)
public #interface Counter {
String name() default "";
}
package de.scrum_master.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
#Aspect
public class CounterAspect {
#Around("execution(* *.*(..)) && #annotation(counter)")
public void myBeforeLogger(ProceedingJoinPoint joinPoint, Counter counter) {
System.out.println(joinPoint + " -> " + counter.name());
}
}
Application module:
<?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>de.scrum-master</groupId>
<artifactId>aspectj-ltw-test-multi-module</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>de.scrum-master</groupId>
<artifactId>application</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>de.scrum-master</groupId>
<artifactId>aspect</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
-javaagent:${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar
</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
package de.scrum_master.app;
import de.scrum_master.aspect.Counter;
public class MyCounter {
#Counter(name = "call_count")
public void count() {}
}
package de.scrum_master.app;
import spark.Spark;
import static spark.Spark.get;
public class CounterApp {
public static void main(String[] args) {
get("/counter", (req, res) -> {
new MyCounter().count();
return "I ALREADY CALLED COUNTER ASPECT ON METHOD:MyCounter().count()";
});
System.out.println("Application starting on port :"+ Spark.port());
}
}
NOTE: If i call below URL my annotation should be processed. But it is not!
http://localhost:4567/counter
Well, first you forgot to add Spark Core to your application module's dependencies, you only defined the version in the parent POM's dependency management section. Otherwise the Maven project will not even compile because of the unknown imports.
Furthermore, the same I told you in my comment to your first question applies:
You attach the Java agent via command line, just like you do for the test.
As an example I added Exec Maven plugin to your application POM and configured it to run your sample main class:
<!-- (...) -->
<properties>
<main-class>de.scrum_master.app.CounterApp</main-class>
</properties>
<!-- (...) -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<executable>java</executable>
<arguments>
<argument>
-javaagent:${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar
</argument>
<argument>-classpath</argument>
<!-- automatically creates the classpath using all project dependencies, also adding the project build directory -->
<classpath/>
<argument>${main-class}</argument>
</arguments>
</configuration>
</plugin>
<!-- (...) -->
Then you run your build and subsequently run the application:
$ mvn clean install
(...)
$ cd application
$ mvn exec:exec
(...)
[INFO] --------------------< de.scrum-master:application >---------------------
[INFO] Building application 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.4.0:exec (default-cli) # application ---
[AppClassLoader#2aae9190] info AspectJ Weaver Version 1.9.4 built on Friday May 10, 2019 at 08:43:10 PDT
[AppClassLoader#2aae9190] info register classloader jdk.internal.loader.ClassLoaders$AppClassLoader#2aae9190
[AppClassLoader#2aae9190] info using configuration file:/C:/Users/alexa/.m2/repository/de/scrum-master/aspect/1.0-SNAPSHOT/aspect-1.0-SNAPSHOT.jar!/META-INF/aop.xml
[AppClassLoader#2aae9190] info register aspect de.scrum_master.aspect.CounterAspect
(...)
Application starting on port :4567
[AppClassLoader#2aae9190] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified
(...)
[AppClassLoader#2aae9190] info processing reweavable type de.scrum_master.aspect.CounterAspect: de\scrum_master\aspect\CounterAspect.aj
[AppClassLoader#2aae9190] info successfully verified type de.scrum_master.aspect.CounterAspect exists. Originates from de\scrum_master\aspect\CounterAspect.aj
Then call your URL http://localhost:4567/counter and check the console output of your running server:
execution(void de.scrum_master.app.MyCounter.count()) -> call_count
The full commit I added to the repository generated for the previous question is here.
I have a problem with controller mappings in Spring Boot.
After I added the Spring-JPA dependency, none of my mappings work anymore.
Deleting the spring-boot-starter-data-jpa dependency helps but usage of JPA is intendend
The controller class is located in a subpackage under the class containing the main method
The Application starts and throws no exceptions. Connection to the database is also working
Mappings when JPA dependency is added:
2018-03-25 16:02:14.550 INFO 1820 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-25 16:02:14.551 INFO 1820 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
Mappings after JPA dependency is removed (how it's expected to be):
2018-03-25 16:28:35.907 INFO 1032 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/ || /index],methods=[GET]}" onto public java.lang.String com.aggrogator.controller.frontend.HomeController.getHome(org.springframework.ui.Model)
2018-03-25 16:28:35.909 INFO 1032 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[GET || POST]}" onto public java.lang.String com.aggrogator.controller.frontend.HomeController.postLogin(com.aggrogator.model.Login)
2018-03-25 16:28:35.920 INFO 1032 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-25 16:28:35.921 INFO 1032 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
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>com.example</groupId>
<artifactId>Aggrogator</artifactId>
<version>${version.number}</version>
<packaging>jar</packaging>
<name>Aggrogator</name>
<description>News-Aggregator</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.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>
<version.number>${git.commit.id.abbrev}</version.number>
<master.branch>latest</master.branch>
</properties>
<dependencies>
<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>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.4.0-RC2</version>
</dependency>
<!-- Shiro uses SLF4J for logging. We'll use the 'simple' binding
in this example app. See http://www.slf4j.org for more info. -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
<!--Import other Plugins for feature-branches or master-branch-->
<profiles>
<profile>
<id>default</id>
<build>
<plugins>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<id>default</id>
<goals>
<goal>build</goal>
<goal>push</goal>
</goals>
</execution>
</executions>
<configuration>
<repository>damian.space:81/aggrogator/aggrogator</repository>
<tag>${version.number}</tag>
<buildArgs>
<JAR_FILE>${project.build.finalName}.jar</JAR_FILE>
</buildArgs>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>master</id>
<build>
<plugins>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<id>default</id>
<goals>
<goal>build</goal>
<goal>push</goal>
</goals>
</execution>
</executions>
<configuration>
<repository>damian.space:81/aggrogator/aggrogator</repository>
<tag>latest</tag>
<buildArgs>
<JAR_FILE>${project.build.finalName}.jar</JAR_FILE>
</buildArgs>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>revision</goal>
</goals>
</execution>
</executions>
<configuration>
<dateFormat>yyyyMMdd-HHmmss</dateFormat><!-- human-readable part of the version number -->
<dotGitDirectory>${project.basedir}/.git</dotGitDirectory>
<generateGitPropertiesFile>false</generateGitPropertiesFile><!-- somehow necessary. otherwise the variables are not available in the pom -->
</configuration>
</plugin>
</plugins>
</build>
</project>
Application:
package com.aggrogator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class AggrogatorApplication {
public static void main(String[] args) {
SpringApplication.run(AggrogatorApplication.class, args);
}
}
Controller:
package com.aggrogator.controller.frontend;
import com.aggrogator.model.Login;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
#Controller
public class HomeController {
// Important for #ModelAttribute to work below!
#ModelAttribute("login")
public Login getLoginObject() {
return new Login();
}
#RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
#RequiresRoles(logical = Logical.OR, value = {"admin","emperor"})
public String getHome(Model model){
return "index";
}
#RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
public String postLogin(#ModelAttribute("login") Login login){
return "login";
}
}
Application.properties:
shiro.loginUrl = /login
# Let Shiro Manage the sessions
shiro.userNativeSessionManager = true
# disable URL session rewriting
shiro.sessionManager.sessionIdUrlRewritingEnabled = false
spring.datasource.url=jdbc:mysql://localhost:3306/aggrogator
spring.datasource.username=user
spring.datasource.password=pw
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Thank you in advance for your help!
Update
Found out some more information
If i add the dependency "shiro-spring" instead of "shiro-spring-boot-web-starter" the mappings get added, but following Exception is thrown on request:
org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.
This exception is clearly thrown because no SecurityManager was found while processing shiro tags in the html template. Removing the shiro tags this exception is not thrown anymore, but no security functions are working (all sites accessible).
After some fiddling I was able to reproduce the beforementioned issue by adding some Beans to the Shiro configuration (still using shiro-spring dependency). Also this is the minimum configuration that reproduces the issue of missing mappings:
package com.aggrogator.configuration;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.PropertiesRealm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroWebConfiguration;
import org.apache.shiro.spring.web.config.ShiroWebFilterConfiguration;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
#Configuration
public class ShiroConfig {
#Bean
public Realm realm() {
// uses 'classpath:shiro-users.properties' by default
PropertiesRealm realm = new PropertiesRealm();
// Caching isn't needed in this example, but we can still turn it on
realm.setCachingEnabled(true);
return realm;
}
#Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
// Paths that need to authenticate over the login page
chainDefinition.addPathDefinition("/**", "authc");
// Path for logout. The session calling it wil be logged out
chainDefinition.addPathDefinition("/logout", "logout");
// Paths that shouldn't require authentication like static resources.
chainDefinition.addPathDefinition("/css/**", "anon");
chainDefinition.addPathDefinition("/images/**", "anon");
chainDefinition.addPathDefinition("/js/**", "anon");
chainDefinition.addPathDefinition("/vendor/**", "anon");
return chainDefinition;
}
#Bean
public CacheManager cacheManager() {
// Caching isn't needed in this example, but we will use the MemoryConstrainedCacheManager for this example.
return new MemoryConstrainedCacheManager();
}
/**
* Shiro Thymeleaf dialect like described at
* https://github.com/theborakompanioni/thymeleaf-extras-shiro
* and derived from
* https://shiro.apache.org/web.html#jsp-gsp-tag-library
* #return
*/
#Bean
public ShiroDialect shiroDialect() {
return new ShiroDialect();
}
#Bean
public DefaultPasswordService defaultPasswordService(){
return new DefaultPasswordService();
}
#Bean
public DefaultSecurityManager securityManager(){
DefaultSecurityManager securityManager = new DefaultSecurityManager();
securityManager.setRealm(realm());
return securityManager;
}
#Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
return new LifecycleBeanPostProcessor();
}
#Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean(){
MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
methodInvokingFactoryBean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager");
methodInvokingFactoryBean.setArguments(new Object[]{securityManager()});
return methodInvokingFactoryBean;
}
#Bean
#DependsOn(value="lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
return new DefaultAdvisorAutoProxyCreator();
}
#Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
return authorizationAttributeSourceAdvisor;
}
}
Now it is clear to me that the Shiro configuration is responsible for this problem. I hope that someone here has a deeper understanding of Shiro and its Spring integration.
I found the same problem as you. In the end, after repeated debugging, I confirmed that as long as you use shiro-spring-boot-starter and spring-aspects at the same time, this happens: the controller that uses Shiro's annotations. All RequestMapping will disappear, see the log can confirm that it has not been scanned at all, I think this is a bug of shiro-spring-boot-starter 1.4.0, I later changed to JavaConfig, configure Shiro myself, there is no such phenomenon. Or you can get rid of spring-aspects. My English is very bad, I hope you can understand
I am having some trouble with Hibernate and JPA. I have used Hibernate before but not with JPA so writing my first persistence.xml currently. I get error message " Invalid persistence.xml." or that the entity manager could not be created, depending on how I write my persistence.xml. The code line that fails is
entityManagerFactory = Persistence.createEntityManagerFactory("name");
And the persisted class looks something like
#Entity
#Table( name = "test_tbl" )
public class Test {
private Long _id;
private String _type;
public Position() {
// this form used by Hibernate
}
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy = "increment")
#Column(name = "n_id")
public Long getId() {
return _id;
}
public void setId(Long id) {
this._id = id;
}
#Column(name = "str_type")
public String getType() {
return _type;
}
public void setType(String type) {
this._type = type;
}
And my pom.xml looks like this
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycoolproject</groupId>
<artifactId>Proj</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>Proj</name>
<url>http://maven.apache.org</url>
<properties>
<!-- Skip artifact deployment -->
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.13.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.13.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>4.2.13.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
And this i my Persistence.xml placed in "src/main/java/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="name">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.mycoolproject.Test</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5555/trial"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.user" value="lalala"/>
<property name="javax.persistence.jdbc.password" value="testing"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
It looks like this is Java SE application. You might need to change persistent-unit tag like this:
<persistence-unit name="name" transaction-type="RESOURCE_LOCAL">
in Java SE you don't have JTA transactions, which are default.