#ContextConfiguration doesn't create transaction proxy - java

I'm trying create some kind of integration test environment and encountered with issue when Test Context Framework doesn't create transaction proxies for my beans. My code:
JUnit class: FileServiceImplTest
#RunWith(SpringJUnit4ClassRunner.class)
#ContextHierarchy({
#ContextConfiguration(value = "file:src/main/webapp/WEB-INF/spring/applicationContext-db.xml"),
#ContextConfiguration(value = "file:src/main/webapp/WEB-INF/spring/applicationContext.xml")
})
public class FileServiceImplTest {
#Autowired
private FileService fileService;
#Test
public void testSaveFolder() {
FolderDTO rootFolder = new FolderDTO();
rootFolder.setName("ROOT");
rootFolder.setParentId(null);
rootFolder.setIdPath("/");
rootFolder.setPath("/");
fileService.saveFile(rootFolder);
List<AbstractFileDTO> rootFiles = fileService.getRootFiles();
assertEquals(1, rootFiles.size());
AbstractFileDTO abstractFileDTO = rootFiles.get(0);
assertEquals(rootFolder, abstractFileDTO);
}
}
Test context frame work inject into 'fileService' filed the FileService bean itself, not transaction proxy. It is reason of exception:
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:132)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:697)
at org.sbezgin.p2016.db.dao.impl.FileDAOImpl.getSession(FileDAOImpl.java:69)
at org.sbezgin.p2016.db.dao.impl.FileDAOImpl.saveOrUpdateFile(FileDAOImpl.java:33)
at org.sbezgin.p2016.services.file.impl.FileServiceImpl.saveFile(FileServiceImpl.java:41)
at org.sbezgin.p2016.services.file.impl.FileServiceImplTest.testSaveFolder(FileServiceImplTest.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
When I run this code under tomcat everything works fine, issue is appear only during running tests. Please help to fix this.
Rest of my code:
FileServiceImpl
#Transactional
public class FileServiceImpl implements FileService {
private FileDAO fileDAO;
private BeanTransformer beanTransformer;
#Override
public AbstractFileDTO getFileByID(long fileID) {
return null;
}
#Override
public FolderDTO getFolder(long folderID) {
return null;
}
#Transactional(propagation = Propagation.REQUIRED)
#Override
public void saveFile(AbstractFileDTO file) {
Long id = file.getId();
if (id == null) {
AbstractFile fileEntity = (AbstractFile) beanTransformer.transformDTOToEntity(file);
User user = new User();
user.setId(1);
fileDAO.saveOrUpdateFile(user, fileEntity);
}
}
#Override
public void setPermission(long fileD, PermissionDTO perm) {
}
#Override
public void renameFile(long fileID, String newName) {
}
#Override
public void deleteFile(long fileID, boolean recursively) {
}
#Override
public List<AbstractFileDTO> getRootFiles() {
User user = new User();
user.setId(1);
List<AbstractFile> rootFiles = fileDAO.getRootFiles(user);
List<AbstractFileDTO> abstractFileDTOs = new ArrayList<>(rootFiles.size());
abstractFileDTOs.addAll(
rootFiles.stream().map(
rootFile -> (AbstractFileDTO) beanTransformer.transformEntityToDTO(rootFile)
).collect(Collectors.toList())
);
return abstractFileDTOs;
}
#Override
public List<AbstractFileDTO> getChildren(long folderID) {
return null;
}
#Override
public List<AbstractFileDTO> getFilesByType(String javaType) {
return null;
}
public FileDAO getFileDAO() {
return fileDAO;
}
public void setFileDAO(FileDAO fileDAO) {
this.fileDAO = fileDAO;
}
public BeanTransformer getBeanTransformer() {
return beanTransformer;
}
public void setBeanTransformer(BeanTransformer beanTransformer) {
this.beanTransformer = beanTransformer;
}
}
FileDAOImpl.java
public class FileDAOImpl implements FileDAO {
private SessionFactory sessionFactory;
#Override
public AbstractFile getFileByID(User user, long fileID) {
return null;
}
#Override
public Folder getFolder(User user, long folderID) {
return null;
}
#Transactional(propagation = Propagation.REQUIRED)
#Override
public void saveOrUpdateFile(User user, AbstractFile file) {
Session session = getSession();
file.setClassName(file.getClass().getCanonicalName());
file.setOwnerID(user.getId());
session.save(file);
}
#Override
public void saveOrUpdateFiles(User user, List<AbstractFile> files) {
}
#Override
public void deleteFile(User user, long fileID, boolean recursively) {
}
#Override
public List<AbstractFile> getRootFiles(User user) {
Session session = getSession();
Query query = session.createQuery("from AbstractFile as file where file.ownerID = :ownerId and file.parentId is null ");
query.setParameter("ownerId", user.getId());
List list = query.list();
return list;
}
#Override
public List<AbstractFile> getChildren(User user, long folderID) {
return null;
}
#Override
public List<AbstractFile> getFilesByType(User user, String javaType) {
return null;
}
private Session getSession() {
return sessionFactory.getCurrentSession();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean name="dozer" class="org.dozer.DozerBeanMapper" />
<bean name="beanTransformer" class="org.sbezgin.p2016.services.impl.BeanTransformerImpl">
<property name="dozerBeanMapper" ref="dozer"/>
<property name="beanMap">
<map>
<entry key="org.sbezgin.p2016.db.dto.file.FolderDTO" value="org.sbezgin.p2016.db.entity.file.Folder"/>
</map>
</property>
</bean>
<!-- services -->
<bean name="fileService" class="org.sbezgin.p2016.services.file.impl.FileServiceImpl">
<property name="fileDAO" ref="fileDAO" />
<property name="beanTransformer" ref="beanTransformer"/>
</bean>
<!-- dao -->
<bean name="fileDAO" class="org.sbezgin.p2016.db.dao.impl.FileDAOImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
applicationContext-db.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:property-placeholder location="WEB-INF/hibernate.properties" ignore-unresolvable="false"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>org.sbezgin.p2016.db.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
<prop key="hibernate.id.new_generator_mappings">${hibernate.id.new_generator_mappings}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
hibernate.properties
jdbc.driverClassName = org.hsqldb.jdbcDriver
jdbc.url = jdbc:hsqldb:hsql://localhost:9001/xdb
jdbc.username = sa
jdbc.password =
hibernate.dialect = org.hibernate.dialect.HSQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.id.new_generator_mappings = false
hibernate.hbm2ddl.auto = create-drop
pom.xml
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- TEST artifacts -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.2.8</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>p2016</finalName>
<plugins>
<plugin>
<!-- current version -->
<groupId>fr.avianey.mojo</groupId>
<artifactId>hsqldb-maven-plugin</artifactId>
<version>1.0.0</version>
<!--
default value for in memory jdbc:hsqldb:hsql://localhost/xdb
override only values you want to change
-->
<configuration>
<driver>org.hsqldb.jdbcDriver</driver>
<address>localhost</address>
<port>9001</port>
<name>xdb</name>
<username>sa</username>
<password></password>
<validationQuery>SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS</validationQuery>
</configuration>
<!-- call start and stop -->
<executions>
<execution>
<id>start-hsqldb</id>
<phase>process-test-classes</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-hsqldb</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

I found that I had to add #EnableTransactionManagement to my Configuration. Prior to that Spring wasn't running the SpringTransactionAnnotationParser and adding the proxy transaction methods to my bean. I only added it to one test because it will make all of the tests run differently than they test framework wants to (managing transactions itself and rolling them back auto-magically)

Based on Spring Framework's documentation:
In the TestContext framework, transactions are managed by the
TransactionalTestExecutionListener which is configured by default,
even if you do not explicitly declare #TestExecutionListeners on your
test class. To enable support for transactions, however, you must
configure a PlatformTransactionManager bean in the ApplicationContext
that is loaded via #ContextConfiguration semantics. In addition, you must declare Spring’s
#Transactional annotation either at the class or method level for your
tests.
You did define a PlatformTransactionManager in your applicationContext-db.xml but did not add a #Transactional on your FileServiceImplTest class or testSaveFolder method. Add the #Transactional on your test class or methods.

Related

Spring JPA with Hibernate transactions deadlock

I have a Spring (core) 5.3.18 application configured with a mixed XML/annotation-driven approach.
To access the backing MariaDB, I use Hibernate core 5.6.7.Final and JPA (javax.persistence-api:2.2) with an HikariCP 4.0.3 connection pool.
The data source is an HikariDataSource with a default connection pool size of 10, and with the leakDetectionThreshold set to 6 seconds (transactions are really short).
The configured JpaTransactionManager fom spring uses as entityManagerFactory a LocalContainerEntityManagerFactoryBean that configures Hibernate via the HibernateJpaVendorAdapter.
At runtime, with just one thread performing DB operations everything works fine.
When multiple threads start requiring the DB at the same time though, threads get stuck on what seems like a starvation condition, all waiting to retrieve a connection.
HikariCP reports the following leak, reported 10 times for all of the connections available in the pool:
java.lang.Exception: Apparent connection leak detected
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:128)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
In my tests, for N threads running apparently I needed a connection pool size of exactly N*2 to avoid this behaviour, which led me to think that by some mistake (or expected behaviour unknown to me) the application I set up consumes two connections for every transaction, instead of just one.
This would explain why not even one request succeeds when all threads are sent requests at the same time, but it's just my guess: each of them acquires the first connection object at some point, and then when they try to acquire the second they all get stuck at the same time.
I really can't figure out what's happening behind Spring's and JPA's magic though. In my understanding of the documentation, a public method of a #Transactional class be wrapped in a spring proxy that gets the connection just before the transaction occurs, and closes it (actually causing the connection to return to the pool instead of bein phisically closed, see also When are connections returned to the connection pool with Spring JPA (Hibernate) Entity Manager?) after the transactin is committed/rolled-back.
Something's amiss, though. I would really appreciate any help or hint about what to do, I've been stuck on this for ages.
Below is the XML spring configuration. There are no additional persistence.xml nor hibernate.properties/cfg.xml.
<bean id="dataSourceHikari" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<property name="driverClassName" value="org.mariadb.jdbc.Driver" />
<property name="jdbcUrl" value="${db.url}" />
<property name="username" value="${db.user}" />
<property name="password" value="${db.password}" />
<property name="dataSourceProperties">
<props>
<prop key="autoReconnect">true</prop>
<prop key="zeroDateTimeBehavior">convertToNull</prop>
</props>
</property>
<property name="validationTimeout" value="3000" />
<property name="readOnly" value="false" />
<property name="connectionTimeout" value="60000" />
<property name="maxLifetime" value="60000" />
<property name="maximumPoolSize" value="${db.maxPoolSize:10}" />
<property name="leakDetectionThreshold" value="6000" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourceHikari" />
<property name="packagesToScan" value="my.application.package" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
My DB layer instead looks like this below.
Each application thread simply invokes DBLayerClass#createSession(String) on the #Autowired DBLayerClass myDBObj once for every incoming request.
import javax.persistence.EntityManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/* other stuff */
#Component
#Transactional(readOnly = false, rollbackFor = {RuntimeException.class, MyCustomExceptions.class})
public class DBLayerClass {
#PersistenceContext
private EntityManager entityManager;
public Session createSession(String sessionId) throws MyCustomExceptions {
try {
if (getSessionById(sessionId) != null)
throw new MyCustomExceptions("...");
Session session = new Session(sessionId);
entityManager.persist(session);
return session;
} catch (EntityExistsException e) {
throw new MyCustomExceptions("...", e);
} catch (PersistenceException e) {
throw new MyCustomExceptions("...", e);
}
}
private Session getSessionById(String sessionId) throws MyCustomExceptions {
try {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Session> cq = cb.createQuery(Session.class);
Root<Session> from = cq.from(Session.class);
cq.where(cb.equal(from.get("sessionId"), sessionId));
TypedQuery<Session> q = entityManager.createQuery(cq);
return q.getSingleResult();
} catch (NoResultException e) {
return null;
} catch (PersistenceException e) {
throw new MyCustomExceptions("...", e);
}
}
}
The fields on my #Entity classes use #Id #GeneratedValue(strategy = GenerationType.SEQUENCE) annotations for Long primary keys, and other regular annotations such as #Column or #Temporal. Most fancy ones are collections with #OneToMany.
I re-wrote a simpler and basic test scenario, made to start a bunch of worker threads which keep sending db requests in a loop. A handful of createSession(...) might work at first, but the test starves soon enough and the above leaks are reported by HikariCP.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:/META-INF/spring/dao-test.xml" })
public class MyTestClass {
#Autowired
private DBLayerClass db;
#Test
public void testConcurrentUsage() throws Exception {
Callable<Exception> c = new Callable<Exception>() {
private AtomicLong nextId = new AtomicLong(0);
#Override
public Exception call() throws Exception {
try {
long id;
while ((id = nextId.incrementAndGet()) < 100L) {
db.createSession(String.format("session-%d", id));
}
return null;
} catch (Exception e) {
return e;
}
}
};
final int nThreads = 30;
Thread[] threads = new Thread[nThreads];
ArrayList<Future<Exception>> threadResults = new ArrayList<>(nThreads);
for (int i = 0; i < threads.length; i++) {
FutureTask<Exception> threadResult = new FutureTask<>(c);
threadResults.add(threadResult);
threads[i] = new Thread(threadResult);
threads[i].start();
}
for (Future<Exception> result : threadResults) {
Exception e = result.get();
if (e != null) {
for (Thread thread : threads) {
thread.stop();
}
throw e;
}
}
}
Finally, these below are the dependencies:
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.18</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.7.Final</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.23.Final</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
</dependency>

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active]

I connected Spring 5.0.19.RELEASE and Hibernate 5.2.10.Final.
I'm getting an error: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active].
The same error is also obtained with other requests (for example "from News").
The work of the application reaches the DAO layer and executes a query from the database.
When I trying to get information from BD and display this list in the web app.
I'm a newbie in Java.
I tried the options below:
why-org-hibernate-hql-internal-ast-querysyntaxexception-customer-is-not-mapped
Hibernate error - QuerySyntaxException: users is not mapped [from
users]
but it doesn't work.
I hope to get help in my confused situation.
My DataBase in MySQL
CREATE TABLE `news` (
`idnews` int NOT NULL AUTO_INCREMENT,
`title` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`brief` varchar(500) COLLATE utf8_bin DEFAULT NULL,
`content` varchar(5000) COLLATE utf8_bin DEFAULT NULL,
`date` timestamp NULL DEFAULT NULL,
`status` varchar(45) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`idnews`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
Error:
Jun 22, 2021 9:10:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/spring-myproject] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3696)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3585)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:576)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:546)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:655)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:679)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:102)
at myproject.dao.impl.SQLNewsDAO.all(SQLNewsDAO.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at jdk.proxy3/jdk.proxy3.$Proxy26.all(Unknown Source)
at myproject.service.impl.NewsServiceImpl.takeAll(NewsServiceImpl.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at jdk.proxy3/jdk.proxy3.$Proxy27.takeAll(Unknown Source)
at myproject.command.GoToMainIndexPage.execute(GoToMainIndexPage.java:27)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:799)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:873)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:831)
Entity:
package myproject.entity;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="news")
public class News implements Serializable {
private static final long serialVersionUID = 5421029433949953632L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="idnews")
private int idnews;
#Column(name="title")
private String title;
#Column(name="brief")
private String brief;
#Column(name="content")
private String content;
#Column(name="date")
private LocalDateTime date;
#Column(name="status")
private String status;
public News() {
}
public News(int idnews, String title, String brief) {
super();
this.setIdnews(idnews);
this.title = title;
this.setBrief(brief);
}
public News(int idnews, String title, String brief, String content, LocalDateTime date) {
super();
this.setIdnews(idnews);
this.title = title;
this.setBrief(brief);
this.setContent(content);
this.setDate(date);
}
public int getIdnews() {
return idnews;
}
public void setIdnews(int idnews) {
this.idnews = idnews;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBrief() {
return brief;
}
public void setBrief(String brief) {
this.brief = brief;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDate() {
DateTimeFormatter newFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
String formattedDateTime = date.format(newFormat);
return formattedDateTime;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((brief == null) ? 0 : brief.hashCode());
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + idnews;
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
News other = (News) obj;
if (brief == null) {
if (other.brief != null)
return false;
} else if (!brief.equals(other.brief))
return false;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (idnews != other.idnews)
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
#Override
public String toString() {
return "id: " + this.idnews + "\n" +
"title:" + this.title + "\n" +
"brief:" + this.brief + "\n" +
"content: " + this.content + "\n" +
"date: " + this.date + "\n" +
"status: " + this.status;
}
}
Controller layer
package myproject.command;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import myproject.entity.News;
import myproject.service.NewsService;
import myproject.service.ServiceException;
#Controller
#RequestMapping("/mainIndexPage")
public class GoToMainIndexPage {
#Autowired
private NewsService newsService;
#RequestMapping("/showMainPage")
public String execute(Model theModel) throws ServletException, IOException, ServiceException {
List<News> news = newsService.takeAll();
theModel.addAttribute("news", news);
return "main_index_page";
}
}
Service layer
package myproject.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import myproject.dao.DAOException;
import myproject.dao.NewsDAO;
import myproject.entity.News;
import myproject.service.NewsService;
import myproject.service.ServiceException;
#Service
public class NewsServiceImpl implements NewsService {
#Autowired
private NewsDAO newsDAO;
//#Override
#Transactional
public List<News> takeAll() throws ServiceException {
System.out.println(1);
List<News> news;
try {
news = newsDAO.all();
} catch (DAOException e) {
throw new ServiceException(e.getMessage(), e);
}
return news;
}
}
DAO layer
package myproject.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import myproject.dao.DAOException;
import myproject.dao.NewsDAO;
import myproject.entity.News;
#Repository
public class SQLNewsDAO implements NewsDAO {
// need to inject the session factory
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<News> all() throws DAOException {
System.out.println(2);
Session currentSession = sessionFactory.getCurrentSession();
Query<News> theQuery = currentSession.createQuery("from News where status =: active", News.class); /*"from News where status = 'active'"*/
List<News> news = theQuery.getResultList();
return news;
}
}
ApplicationContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="myproject" />
<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven />
<!-- Step 5: Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 6 Add support for reading web resources: css, images, js, etc
... -->
<mvc:resources location="/resources/"
mapping="/resources/**" />
<bean
class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property value="resources/messages" name="basenames" />
</bean>
<!-- Step 7 Define Database DataSource / connection pool -->
<bean id="myDataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/news_management_spring_hibernate?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC" />
<property name="user" value="111" />
<property name="password" value="111" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 8 Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="src.main.java.myproject.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 9 Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 10 Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>by.htp.spring.main</groupId>
<artifactId>spring-myproject</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-myproject Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Generic properties -->
<maven.compiler.release>1.8</maven.compiler.release>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>3.1.0</servlet.version>
<!-- Spring -->
<spring-framework.version>5.0.19.RELEASE</spring-framework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- BD -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- Dependency Spring Framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Other -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.8</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
<!-- New depend -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.4.26.Final</version>
</dependency>
</dependencies>
<build>
<finalName>spring-myproject</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>tomcat-server</server>
</configuration>
</plugin>
<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>
<encoding>${project.build.sourceEncoding}</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
</project>
main_index_page.jsp (view)
<!--News-->
<div class="list_news">
<c:forEach var="AllNewsFromBD" items="${news}"> <!--requestScope.-->
<div class="list_news_block">
<div class="">
<h5 class="title_news">
<c:out value="${AllNewsFromBD.title}" />
</h5>
<p class="">
<c:out value="${AllNewsFromBD.brief}" />
</p>
<c:if test="${sessionScope.auth == true}">
<div class="">
<a href="Controller?command=go_to_one_news_page&idnews=<c:out value="${AllNewsFromBD.idnews}"/>">
<c:out value="${ReadMore}" /></a>
</div>
</c:if>
<br/>
</div>
</div>
</c:forEach>
</div>
There are lot of posts on stackoverflow in which addressing the same issue. But I was unable to find a definite solution for this.
Please help
You could try this:
Query<News> theQuery = currentSession.createQuery("select news from News news where news.status = :active", News.class);
theQuery.setParameter("status", active);
return theQuery.getResultList();

In Spring MVC, what is the correct configuration for using Jaxb annotations for request body?

Currently I have a RESTful service, and I am trying to deserialize a POST request body, that is XML, that is not working. I've tried all solutions out there, but none seem to work. JSON works perfectly with Spring MVC, but getting XML to work is such a pain..
I'm using Spring 5.1.5 version, and using Jaxb for the marshalling and unmarshalling.
The following is what I currently have:
This is my spring mvc configuration:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="my.project.controllers" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter">
<property name="objectMapper" ref="xmlMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true"
p:simpleDateFormat="yyyy-MM-dd"
p:modulesToInstall="com.fasterxml.jackson.module.paramnames.ParameterNamesModule"/>
<bean id="xmlMapper" parent="objectMapper" p:createXmlMapper="true"/>
</beans>
These are my pom.xml dependencies:
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.guice</groupId>
<artifactId>spring-guice</artifactId>
<version>${spring.guice.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${sl4j-log4j.version}</version>
</dependency>
<!-- Other dependencies -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax.annotation.version}</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>${guice.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
This is my RestController:
#RestController
#RequestMapping("issuance")
public class ProtocolController {
#Autowired
private IssuerManager issuerManager;
#PostMapping(value = "init", produces = "application/xml", consumes = "application/xml")
public IssuanceMessageAndBoolean initializeIssuance(#RequestBody final IssuancePolicyAndAttributes ipaa) throws CryptoEngineException {
IssuanceMessageAndBoolean imab = issuerManager.initializeIssuanceProtocol(ipaa);
return imab;
}
This is the object that I am trying to deserialize (IssuancePolicyAndAttributes):
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(
name = "IssuancePolicyAndAttributes",
namespace = "http://abc4trust.eu/wp2/abcschemav1.0",
propOrder = {"issuancePolicy", "attribute"}
)
#XmlRootElement(
name = "IssuancePolicyAndAttributes"
)
public class IssuancePolicyAndAttributes implements Serializable {
private static final long serialVersionUID = 6699648078303838561L;
#XmlElement(
name = "IssuancePolicy",
namespace = "http://abc4trust.eu/wp2/abcschemav1.0",
required = true
)
protected IssuancePolicy issuancePolicy;
#XmlElement(
name = "Attribute",
namespace = "http://abc4trust.eu/wp2/abcschemav1.0"
)
protected List<Attribute> attribute;
public IssuancePolicyAndAttributes() {
}
public IssuancePolicy getIssuancePolicy() {
return this.issuancePolicy;
}
public void setIssuancePolicy(IssuancePolicy value) {
this.issuancePolicy = value;
}
public List<Attribute> getAttribute() {
if (this.attribute == null) {
this.attribute = new ArrayList();
}
return this.attribute;
}
}
And this is my XML that I am sending as the request body:
<abc:IssuancePolicyAndAttributes
xmlns:abc="http://abc4trust.eu/wp2/abcschemav1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://abc4trust.eu/wp2/abcschemav1.0 ../../../../../../../../abc4trust-xml/src/main/resources/xsd/schema.xsd">
<abc:IssuancePolicy Version="1.0">
<abc:PresentationPolicy PolicyUID="http://ticketcompany.com/tickets/issuance/policy">
<abc:Pseudonym Exclusive="true" Scope="http://ticketcompany.com/tickets/vip" Established="false"
Alias="#nym"/>
<abc:Message>
<abc:Nonce>KNsRu9cGzkaeabogeRVV</abc:Nonce>
<abc:ApplicationData>
<abc:TestApplicationData>
<abc:Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xsi:type="xs:string">Some data
</abc:Data>
</abc:TestApplicationData>
</abc:ApplicationData>
</abc:Message>
</abc:PresentationPolicy>
<abc:CredentialTemplate SameKeyBindingAs="#nym">
<abc:CredentialSpecUID>http://MyFavoriteSoccerTeam/tickets/vip</abc:CredentialSpecUID>
<abc:IssuerParametersUID>http://ticketcompany/MyFavoriteSoccerTeam/issuance:idemix</abc:IssuerParametersUID>
<abc:UnknownAttributes/>
</abc:CredentialTemplate>
</abc:IssuancePolicy>
<abc:Attribute>
<abc:AttributeUID>-5027215341191833963</abc:AttributeUID>
<abc:AttributeDescription DataType="xs:string" Encoding="urn:abc4trust:1.0:encoding:string:sha-256"
Type="FirstName">
<abc:FriendlyAttributeName lang="en">first name</abc:FriendlyAttributeName>
<abc:FriendlyAttributeName lang="da">fornavn</abc:FriendlyAttributeName>
</abc:AttributeDescription>
<abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">John
</abc:AttributeValue>
</abc:Attribute>
<abc:Attribute>
<abc:AttributeUID>-2715953330829768453</abc:AttributeUID>
<abc:AttributeDescription DataType="xs:string" Encoding="urn:abc4trust:1.0:encoding:string:sha-256"
Type="LastName">
<abc:FriendlyAttributeName lang="en">last name</abc:FriendlyAttributeName>
<abc:FriendlyAttributeName lang="da">efternavn</abc:FriendlyAttributeName>
</abc:AttributeDescription>
<abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Dow
</abc:AttributeValue>
</abc:Attribute>
<abc:Attribute>
<abc:AttributeUID>-2231744817504418816</abc:AttributeUID>
<abc:AttributeDescription DataType="xs:date" Encoding="urn:abc4trust:1.0:encoding:date:unix:signed"
Type="Birthday">
<abc:FriendlyAttributeName lang="en">birthday</abc:FriendlyAttributeName>
<abc:FriendlyAttributeName lang="da">fødselsdag</abc:FriendlyAttributeName>
</abc:AttributeDescription>
<abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1985-05-05Z
</abc:AttributeValue>
</abc:Attribute>
<abc:Attribute>
<abc:AttributeUID>-2231744817504418826</abc:AttributeUID>
<abc:AttributeDescription DataType="xs:date" Encoding="urn:abc4trust:1.0:encoding:date:unix:signed"
Type="Matchday">
<abc:FriendlyAttributeName lang="en">Match day</abc:FriendlyAttributeName>
<abc:FriendlyAttributeName lang="da">Kamp dag</abc:FriendlyAttributeName>
</abc:AttributeDescription>
<abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">2013-08-07Z
</abc:AttributeValue>
</abc:Attribute>
<abc:Attribute>
<abc:AttributeUID>-1231744817504418817</abc:AttributeUID>
<abc:AttributeDescription Type="MemberNumber" DataType="xs:integer"
Encoding="urn:abc4trust:1.0:encoding:integer:unsigned">
<abc:FriendlyAttributeName lang="en">VIP member id</abc:FriendlyAttributeName>
<abc:FriendlyAttributeName lang="da">VIP medlems nummer</abc:FriendlyAttributeName>
</abc:AttributeDescription>
<abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:integer">23784638726
</abc:AttributeValue>
</abc:Attribute>
</abc:IssuancePolicyAndAttributes>
When I debug and check the value of the variable ipaa of the RestController, the variable itself is instantiated but all of its members are null, which indicates the unmarshalling is not occurring correctly.
What am I doing wrong?
change the name of xml element
#XmlElement(name = "abc:IssuancePolicy", namespace = "http://abc4trust.eu/wp2/abcschemav1.0", required = true)
protected IssuancePolicy issuancePolicy;
#XmlElement(name = "abc:Attribute", namespace = "http://abc4trust.eu/wp2/abcschemav1.0")
protected List<Attribute> attribute;

Not able to invoke REST service in spring RestController

I have implemented REST webservice using Spring 5 #RestController.
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ag</groupId>
<artifactId>myFirstWeb</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>myFirstWeb Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jdbc</artifactId>
<version>1.0.0.M3</version>
</dependency>
<!-- ojdbc6.jar example -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-libs-milestone</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<build>
<finalName>myFirstWeb</finalName>
</build>
</project>
web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:ctx="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<ctx:component-scan base-package="com.*" />
<ctx:annotation-config />
<mvc:annotation-driven />
<!-- JSON Support -->
<bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:XE" />
<property name="username" value="SYSTEM" />
<property name="password" value="xlri#123" />
</bean>
</beans>
REST service
package com.pk;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.pk.services.StudentService;
import com.pk.vo.StudentVO;
#RestController
#RequestMapping(value="/first")
public class MyFirst{
public MyFirst() {
System.out.println("Webservice 'MyFirst' initialised...");
}
#Autowired
#Qualifier("studentService")
private StudentService service;
public StudentService getService() {
return service;
}
public void setService(StudentService service) {
this.service = service;
}
#RequestMapping(value="/hello",method=RequestMethod.GET,produces="application/json")
public ResponseEntity<String> sayHello() {
StringBuffer strb = new StringBuffer();
strb.append("{")
.append("\"message\"")
.append(":")
.append("\"Hello, this is my first message\"")
.append("}");
ResponseEntity<String> responseEntity = new ResponseEntity<String>(strb.toString(), HttpStatus.OK);
return responseEntity;
}
#RequestMapping(value="/students",method=RequestMethod.GET,produces="application/json")
public List<StudentVO> getAllStudents(){
List<StudentVO> list = null;
System.out.println(" Studeent list ");
try {
list = this.service.getAll();
}catch(Exception e) {
e.printStackTrace();
}
return list;
}
}
I am able to invoke
/spring/first/hello
But I am not able to invoke
/spring/first/students
The error it gives is:
HTTP Status 406 – Not Acceptable
Then I changed my code to,
#RequestMapping(value="/students",method=RequestMethod.GET,produces="application/json")
public ResponseEntity<List<StudentVO>> getAllStudents(){
List<StudentVO> list = null;
ResponseEntity<List<StudentVO>> responseEntity = null;
System.out.println(" Studeent list ");
try {
list = this.service.getAll();
for(StudentVO vo : list) {
System.out.println(vo);
}
responseEntity = new ResponseEntity<List<StudentVO>>(list,HttpStatus.OK);
}catch(Exception e) {
e.printStackTrace();
}
return responseEntity;
}
It's not working as well, although it prints all the vo's in console.
It gives the same error:
HTTP Status 406 – Not Acceptable
StudentVO.java
package com.pk.vo;
import java.io.Serializable;
public class StudentVO implements Serializable{
/**
*
*/
private static final long serialVersionUID = 145L;
private Integer studentId;
private String studentName;
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
#Override
public int hashCode(){
int hash = 31;
int hashFromId = this.studentId.hashCode();
hash = (7 * hash) + hashFromId;
return hash;
}
#Override
public boolean equals(Object object) {
boolean flag = false;
StudentVO vo = (StudentVO) object;
if(vo != null && this.studentId.intValue() == vo.studentId.intValue()) {
flag = true;
}
return flag;
}
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("\nStudent-ID ").append(this.studentId).append(",\tStudent-Name ").append(this.studentName);
return strb.toString();
}
}
Can you please tell me where I am wrong?
Add the following dependencies to your pom.xml, you get the error because spring can not serialize your List to JSON, this is handled by JSON however with spring 4.1.1+ you have to add these dependencies yourself:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>

Spring AOP: Aspect class is not executed

I have defined an aspect which should be executed when the method getFirstName() is called on the User object. But it does not happen.
My Aspect class:
#Component
#Aspect
public class JpaGetFirstNameAspect {
#Pointcut("execution(* de.playground.model.User.getFirstName(..))")
public void pointCutSetFirstName() {
}
#Before("pointCutGetFirstName()")
public void beforeGetFirstName(JoinPoint joinPoint) {
System.out.println(">>>> Before retrieving first name ... " + joinPoint.getSignature().getName());
}
#After("pointCutGetFirstName()")
public void afterGetFirstName() {
System.out.println(">>>> After execution of getFirstName method ... ");
}
#AfterReturning(pointcut = "pointCutGetFirstName()", returning = "firstName")
public void afterReturningGetFirstName(JoinPoint joinPoint, String firstName) {
System.out.println("<<<< " + joinPoint.getSignature().getName());
System.out.println("<<<< returned first name of user " + firstName);
}
#AfterThrowing(pointcut = "pointCutGetFirstName()", throwing = "exc")
public void afterThrowingGetFirstName(Exception exc) {
System.out.println("|||| Retrieved Exception from getFirstName method ... " + exc.toString());
}
}
My application-context.xml:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
">
<context:annotation-config />
<context:load-time-weaver />
<context:component-scan base-package="de.playground.service" />
</beans>
My testclass:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/test/resources/META-INF/spring/application-context.xml" })
public class AspectIntegrationTest {
#Autowired
private GenericApplicationContext context;
private ClassPathXmlApplicationContext ctx;
public AspectIntegrationTest() {
}
#AfterClass
public static void tearDownClass() {
}
#BeforeClass
public static void setUpClass() {
}
#Before
public void setUp() throws Exception {
ctx = new ClassPathXmlApplicationContext();
}
#After
public void tearDown() {
}
#Test
public void testHijackingUser() {
User user1 = new User();
user1.setCreatedOn(new Date());
user1.setLastModified(new Date());
user1.setFirstName("Max");
user1.setLastName("Mustermann");
user1.setUsername("max.mustermann");
user1.setPassword("start123");
System.out.println(">user 1 = " + user1.getFirstName());
assertNotNull(user1);
}
}
My aop.xml:
<!DOCTYPE aspectj PUBLIC
"-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
<weaver options="-Xset:weaveJavaxPackages=true -verbose -showWeaveInfo">
<!-- only weave classes in this package -->
<include within="de.playground.service.*" />
</weaver>
<aspects>
<!-- use only this aspect for weaving -->
<aspect name="de.playground.aspect.JpaGetFirstNameAspect" />
</aspects>
</aspectj>
My 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>
<parent>
<groupId>de.playground.platform</groupId>
<artifactId>playground-dev</artifactId>
<version>0.0.2-SNAPSHOT</version>
</parent>
<artifactId>playground-script</artifactId>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${version.aspectj}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${version.aspectj}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<version.aspectj>1.8.5</version.aspectj>
<version.spring>4.1.6.RELEASE</version.spring>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>once</forkMode>
<argLine>-javaagent:"${settings.localRepository}/org/springframework/spring-instrument/${version.spring}/spring-instrument-${version.spring}.jar"</argLine>
<useSystemClassloader>true</useSystemClassloader>
</configuration>
</plugin>
</plugins>
</build>
</project>
Got it working. My updated pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>once</forkMode>
<argLine>-javaagent:"${settings.localRepository}/org/springframework/spring-instrument/${version.spring}/spring-instrument-${version.spring}.jar"</argLine>
<useSystemClassloader>true</useSystemClassloader>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<showWeaveInfo>true</showWeaveInfo>
<source>1.7</source>
<target>1.7</target>
<Xlint>ignore</Xlint>
<complianceLevel>1.7</complianceLevel>
<encoding>UTF-8</encoding>
<verbose>false</verbose>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${version.aspectj}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${version.aspectj}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>

Categories