Error creating spring boot bean - "The blank final field em may not have been initialized" - spring

I am a newbie for the spring boot framework. I have successfully done crud operation. After that I have decided that to do Advanced search concepts. Please see the code below, which I used.
package com.lean.repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.repository.JpaRepository;
import com.lean.entity.Merchant;
public interface MerchantDao extends JpaRepository<Merchant, Long> {
EntityManager em;
public List<Merchant> findAllByNameIn(Set<String> name);
public default List<Merchant> findMerchantList(String name, String email) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Merchant> cq = cb.createQuery(Merchant.class);
Root<Merchant> book = cq.from(Merchant.class);
List<Predicate> predicates = new ArrayList<>();
if (name != null) {
predicates.add(cb.equal(book.get("name"), name));
}
if (email != null) {
predicates.add(cb.equal(book.get("email"), email));
}
cq.where(predicates.toArray(new Predicate[0]));
return em.createQuery(cq).getResultList();
};
}
Here, I am getting the below error.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'merchantDao': Invocation of init method failed; nested exception is java.lang.Error: Unresolved compilation problem:
The blank final field em may not have been initialized
When I am trying to get the"EntityManager em" entity object, I will get the above error.
Please help someone to fix the issue. Thanks in advance

Try this :-
#PersistenceContext
private EntityManager em;
Also check for below dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>

Related

Injection of CommandGateway not work in Quarkus using AxonIq

I have a microservice in Quarkus which implementing CQRS/Event sourcing using AxonIq Framework. I Already made it using Spring boot and everythings it's ok. I would like to migrate it in Quarkus but I have error during maven compilation probably because the Ioc. When CDI try to create the service I think he can inject Axon CommandGateway and QueryGateway.
[ERROR] Failed to execute goal io.quarkus.platform:quarkus-maven-plugin:2.7.1.Final:build (default) on project domain: Failed to build quarkus application: io.quarkus.builder.BuildExce
ption: Build failure: Build failed due to errors
[ERROR] [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: Found 2 deployment problems:
[ERROR] [1] Unsatisfied dependency for type org.axonframework.Commandhandling.CommandGateway and qualifiers [#Default]
[ERROR] - java member: com.omb.commands.MyAggregateCommandService().commandGateway
[ERROR] - declared on CLASS bean [types=[com.omb.commands.MyAggregateCommandService, java.lang.Object], qualifiers=[#Default, #Any], target=com.omb.commands.MyAggregateCommandService]
Configuration
package com.omb..configuration;
import com.omb..MyAggregate;
import com.omb..commands.MyAggregateCommandService;
import com.omb..mongo.MongoMyAggregateProjector;
import com.omb..queries.MyAggregateQueryService;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.axonframework.config.Configurer;
import org.axonframework.config.DefaultConfigurer;
import org.axonframework.eventsourcing.eventstore.EventStorageEngine;
import org.axonframework.extensions.mongo.DefaultMongoTemplate;
import org.axonframework.extensions.mongo.eventsourcing.tokenstore.MongoTokenStore;
import org.axonframework.serialization.xml.XStreamSerializer;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
#ApplicationScoped
public class AxonConfiguration {
#Produces
public org.axonframework.config.Configuration getAxonConfiguration(MongoMyAggregateProjector MyAggregateProjector, MongoDatabase database, EventStorageEngine eventStorageEngine) {
XStreamSerializer serializer = XStreamSerializer.defaultSerializer();
Configurer configurer = DefaultConfigurer
.defaultConfiguration()
.configureAggregate(MyAggregate.class)
.eventProcessing(conf -> conf
.registerTokenStore(config -> MongoTokenStore.builder()
.mongoTemplate(
DefaultMongoTemplate.builder()
// optionally choose collection names here
.mongoDatabase(database)
.build())
.serializer(serializer)
.build()))
.registerEventHandler(conf -> MyAggregateProjector)
.registerQueryHandler(conf -> MyAggregateProjector)
.configureEmbeddedEventStore(conf -> eventStorageEngine);
return configurer.start();
}
#Produces
public MongoDatabase mongoDatabase(MongoClient client) {
return client.getDatabase("MyAggregate");
}
#Produces
#ApplicationScoped
public MyAggregateQueryService queryService(org.axonframework.config.Configuration configuration) {
return new MyAggregateQueryService(configuration.queryGateway());
}
#Produces
#ApplicationScoped
public MyAggregateCommandService commandService(org.axonframework.config.Configuration configuration) {
return new MyAggregateCommandService(configuration.commandGateway());
}
}
Service :
package com.omb..commands;
import com.omb..models.MyAggregateDTO;
import org.axonframework.commandhandling.gateway.CommandGateway;
import javax.enterprise.context.ApplicationScoped;
import java.util.concurrent.CompletableFuture;
#ApplicationScoped
public class MyAggregateCommandService {
CommandGateway commandGateway;
public MyAggregateCommandService(CommandGateway commandGateway) {
this.commandGateway = commandGateway;
}
public CompletableFuture<String> createMyAggregate(final MyAggregateDTO MyAggregate) {
return commandGateway.send(new CreateMyAggregateCommand(MyAggregate.id(), MyAggregate.name()));
}
public CompletableFuture<MyAggregateDTO> updateMyAggregate(final String MyAggregateId, final MyAggregateDTO MyAggregate) {
if(MyAggregate.id().equals(MyAggregateId)) {
return commandGateway.send(new UpdateMyAggregateCommand(MyAggregate.id(), MyAggregate.name()));
} else {
throw new IllegalArgumentException("Identifiers are not the same, does not update");
}
}
}
Controller :
package com.omb;
import com.omb..commands.MyAggregateCommandService;
import com.omb..models.MyAggregateDTO;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
#Path("/commands/MyAggregate")
public class MyAggregateCommandController {
private MyAggregateCommandService MyAggregateCommandService;
public MyAggregateCommandController(MyAggregateCommandService MyAggregateCommandService) {
this.MyAggregateCommandService = MyAggregateCommandService;
}
#POST
#Path("/create")
public CompletableFuture<String> createMyAggregate(#Valid MyAggregateCreateInput MyAggregate) {
MyAggregateDTO MyAggregateDTO = new MyAggregateDTO(UUID.randomUUID().toString(), MyAggregate.name());
return MyAggregateCommandService.createMyAggregate(MyAggregateDTO);
}
#PUT
#Path("/{MyAggregateId}")
public CompletableFuture<MyAggregateDTO> updateMyAggregate(#PathParam("MyAggregateId") String MyAggregateId, MyAggregateDTO MyAggregate) {
MyAggregateDTO MyAggregateDTO = new MyAggregateDTO(MyAggregate.id(), MyAggregate.name());
return MyAggregateCommandService.updateMyAggregate(MyAggregateId,MyAggregateDTO);
}
/* #ExceptionHandler(value = Exception.class)
public ResponseEntity<String> handle(Exception e) {
return ResponseEntity.badRequest().body(e.getMessage());
}*/
}
dependency
<dependency>
<groupId>org.axonframework.extensions.mongo</groupId>
<artifactId>axon-mongo</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-test</artifactId>
<scope>test</scope>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-mongodb-panache</artifactId>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-configuration</artifactId>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-modelling</artifactId>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-messaging</artifactId>
</dependency>
<!-- Quarkus -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-core</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-reactive-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-validator</artifactId>
</dependency>
I had the same issue, one of the reasons can be that your bean is brought by a dependency and to fix it you need to add an empty beans.xml in main/resources/META-INF in this dependency in order for Quarkus to discover the beans as indicated by the documentation
Relevant extract:
The bean archive is synthesized from:
the application classes,
dependencies that contain a beans.xml descriptor (content is ignored),
dependencies that contain a Jandex index - META-INF/jandex.idx,
dependencies referenced by quarkus.index-dependency in application.properties,
and Quarkus integration code.

hibernate ClassCastException with mvn spring-boot:run

when I start the server using the jar:
java -jar core-0.0.1-SNAPSHOT.jar
then everything works fine.
But when i use the maven plugin:
mvn spring-boot:run
then i get the following error message:
2020-09-28 23:09:46.633 DEBUG 13970 --- [ main] d.j.p.server.core.ServerApplication : Running with Spring Boot v2.1.6.RELEASE, Spring v5.1.8.RELEASE
2020-09-28 23:09:46.634 INFO 13970 --- [ main] d.j.p.server.core.ServerApplication : No active profile set, falling back to default profiles: default
2020-09-28 23:09:49.120 ERROR 13970 --- [ main] o.s.b.web.embedded.tomcat.TomcatStarter : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message:
Error creating bean with name 'sessionRepositoryFilterRegistration' defined in class path resource [org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.class]:
Unsatisfied dependency expressed through method 'sessionRepositoryFilterRegistration' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'org.springframework.boot.autoconfigure.session.JdbcSessionConfiguration$SpringBootJdbcHttpSessionConfiguration': Unsatisfied dependency expressed through method 'setTransactionManager' parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseTransactionManager' defined in class path resource [de/jwt/project/server/core/config/BaseDataSourceConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.PlatformTransactionManager]:
Factory method 'baseTransactionManager' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'baseEntityManager' defined in class path resource [de/jwt/project/server/core/config/BaseDataSourceConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]:
Factory method 'baseEntityManager' threw exception; nested exception is java.lang.ClassCastException: class java.lang.Class cannot be cast to class java.lang.reflect.ParameterizedType
(java.lang.Class and java.lang.reflect.ParameterizedType are in module java.base of loader 'bootstrap')
2020-09-28 23:09:49.167 WARN 13970 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2020-09-28 23:09:49.188 ERROR 13970 --- [ main] o.s.boot.SpringApplication : Application run failed
Unfortunately I have no idea what the cause can be,
i am grateful for every 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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>de.jwt.project.server</groupId>
<artifactId>core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Server</name>
<description>Server</description>
<properties>
<project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
<project.reporting.outputEncoding>ISO-8859-1</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<!--<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-bom</artifactId>
<version>Bean-SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>-->
<repositories>
<repository>
<id>jcenter</id>
<url>https://jcenter.bintray.com/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-bom</artifactId>
<version>Bean-SR3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
<!-- send email -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-properties-migrator</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>de.jwt.project.remoteservice</groupId>
<artifactId>de.jwt.project.remoteservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/net.imagej/ij -->
<dependency>
<groupId>net.imagej</groupId>
<artifactId>ij</artifactId>
<version>1.52i</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!--
<dependency>
<groupId>de.agital.project.caritas</groupId>
<artifactId>de.agital.project.caritas</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>-->
<dependency>
<groupId>org.wickedsource.docx-stamper</groupId>
<artifactId>docx-stamper</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>6.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
#SpringbootApplication main class
package de.jwt.project.server.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.naming.NoPermissionException;
import javax.servlet.Filter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import de.jwt.project.database.components.ModelResource;
import de.jwt.project.database.components.Referenz;
import de.jwt.project.database.tenant.Account;
import de.jwt.project.database.tenant.Geschaeftspartner;
import de.jwt.project.database.tenant.GespeicherteAbfrage;
import de.jwt.project.database.tenant.Instanz;
import de.jwt.project.database.tenant.Instanzwert;
import de.jwt.project.database.tenant.Rolle;
import de.jwt.project.database.tenant.Team;
import de.jwt.project.database.tenant.Vertrag;
import de.jwt.project.database.tenant.VertragInstanzBez;
import de.jwt.project.database.types.OperationsForQuery;
import de.jwt.project.remoteservice.components.ReferenzHierachy;
import de.jwt.project.server.core.dao.tenant.AccountDao;
import de.jwt.project.server.core.dao.tenant.RolleDao;
import de.jwt.project.server.core.migration.MetadataGenerator;
import de.jwt.project.server.core.multitenant.MultiTenantFilter;
import de.jwt.project.server.core.service.AccountService;
import de.jwt.project.server.core.service.ResourceService;
#SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
#SuppressWarnings("unused")
public class ServerApplication {
private static Account login(final ConfigurableApplicationContext context, String username, String password,
String tenant) {
final AccountDao accountDao = context.getBean(AccountDao.class);
final RolleDao rolleDao = context.getBean(RolleDao.class);
final AccountService accountService = context.getBean(AccountService.class);
final MetadataGenerator metaGen = context.getBean(MetadataGenerator.class);
Account admin = null;
try {
admin = (Account) accountService.loadUserByUsername(username);
} catch (UsernameNotFoundException e) {
e.printStackTrace();
}
if (admin == null) {
admin = new Account();
admin.setUsername(username);
admin.setPassword(password);
Rolle rolle = rolleDao.findByDescription("Administrator");
if (rolle == null) {
rolle = new Rolle();
rolle.setDescription("Administrator");
rolle = rolleDao.save(rolle);
}
Set<Rolle> rollen = new HashSet();
rollen.add(rolle);
admin = accountService.save(admin);
admin.setRoles(rollen);
admin = accountService.save(admin);
}
metaGen.execute(admin, "metadaten_caritas.xml");
return admin;
}
private static void encryptPW(final ConfigurableApplicationContext context) {
final BCryptPasswordEncoder enc = new BCryptPasswordEncoder();
final AccountDao accountDao = context.getBean(AccountDao.class);
// -------------------------------
final List<Account> lstAccount = accountDao.findAll();
for (final Account account : lstAccount) {
if (!account.isEncrypted()) {
account.setPassword(enc.encode(account.getPassword()));
account.setEncrypted(true);
accountDao.save(account);
}
}
}
public static void main(final String[] args) throws Throwable {
final ConfigurableApplicationContext context = SpringApplication.run(ServerApplication.class, args);
Properties properties = new Properties();
try (InputStream inputStream = ServerApplication.class.getClassLoader().getResourceAsStream("application.properties")) {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
String username = properties.getProperty("backenduser");
String pw = properties.getProperty("backenduserpassword");
Account account = login(context, username, pw, "carritas_db");
// Verschlüssele Passwörter im Klartext
encryptPW(context);
//createAuskunftverlangen(context, account);
}
private static void createAuskunftverlangen(ConfigurableApplicationContext context, Account account) {
final ResourceService ressourceService = context.getBean(ResourceService.class);
try {
GespeicherteAbfrage abfrage = (GespeicherteAbfrage) ressourceService
.getByDescription(GespeicherteAbfrage.class, "Auskunftsverlangen");
if (abfrage != null) {
return;
}
ReferenzHierachy hierachy = new ReferenzHierachy(Instanzwert.class, true);
hierachy.addJoin(Instanz.class, "instanz", "id", "instanz", null);
hierachy.addJoin(VertragInstanzBez.class, "id", "instanz", "vib", "instanz");
hierachy.addJoin(Vertrag.class, "vertrag", "id", "vertrag", "vib");
hierachy.addCondition(hierachy.createFilter(Referenz.class, "geschaeftspartner", OperationsForQuery.EQUALS,
new Geschaeftspartner().toReferenz(), "instanz"));
hierachy.addAdditionalField(String.class, "wert", null, "gespeicherter Wert");
hierachy.addAdditionalField(ModelResource.class, "referenz", null, "gespeicherte Referenz");
hierachy.addAdditionalField(String.class, "vertragsnummer", "vertrag", "Vertragsnummer");
hierachy.addAdditionalField(String.class, "description", "vertrag", "Vertrag");
Team team = new Team(account);
abfrage = new GespeicherteAbfrage();
abfrage.setBesitzer(team.toReferenz());
abfrage.setDescription("Auskunftsverlangen");
abfrage.setAbfrage(hierachy.serialize());
abfrage = (GespeicherteAbfrage) ressourceService.save(abfrage);
} catch (IOException | NoPermissionException | ClassNotFoundException e) {
e.printStackTrace();
return;
}
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean someFilterRegistration() {
final FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(someFilter());
registration.addUrlPatterns("/api/auth/login/*");
registration.setName("MultiTenantFilter");
registration.setOrder(1);
return registration;
}
public Filter someFilter() {
return new MultiTenantFilter();
}
}
BaseDataSourceConfig:
package de.jwt.project.server.core.config;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
#Configuration
#EnableJpaRepositories(
basePackages = "de.jwt.project.server.core.dao.base",
entityManagerFactoryRef = "baseEntityManager",
transactionManagerRef = "baseTransactionManager"
)
public class BaseDataSourceConfig {
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean baseEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPersistenceUnitName("persistence.base");
em.setDataSource(baseDataSource());
em.setPackagesToScan("de.jwt.project.database.base", "de.jwt.project.database.components");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.afterPropertiesSet();
return em;
}
#Primary
#Bean
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource baseDataSource() {
DataSource ds = DataSourceBuilder.create()
.build();
return ds;
}
#Primary
#Bean
public PlatformTransactionManager baseTransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
baseEntityManager().getObject());
return transactionManager;
}
}
The image shows the point where the exception is thrown.
The cast exception is thrown in the AttributeConverterDefinition.resolveType() method.
And her the code from the ReferenzConverter.class.
This is the class which cause the cast exception.
package de.jwt.project.database.components;
import java.util.UUID;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
#Converter(
autoApply = true
)
public class ReferenzConverter<T extends ModelResource> implements AttributeConverter<Referenz<T>, UUID> {
public ReferenzConverter() {
}
public UUID convertToDatabaseColumn(Referenz<T> attribute) {
return attribute == null ? null : attribute.getId();
}
public Referenz<T> convertToEntityAttribute(UUID dbData) {
if (dbData == null) {
return null;
} else {
Referenz ref = new Referenz(dbData);
return ref;
}
}
}
.....................................................

Unit Testing Freemarker templates in SpringBoot - unable to initialize freemarker configuration

we are using Freemarker for generating the HTML code for the emails our application is going to be sending.
Our usage and configuration is based off of https://github.com/hdineth/SpringBoot-freemaker-email-send
Particularly:
package com.example.techmagister.sendingemail.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
import java.io.IOException;
#Configuration
public class FreemarkerConfig {
#Bean(name="emailConfigBean")
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration(ResourceLoader resourceLoader) {
FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
bean.setTemplateLoaderPath("classpath:/templates/");
return bean;
}
}
However, there is absolutely no information or documentation anywhere, about how to run Unit Tests for this using JUnit 5.
When I added the relevant dependencies
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
versions:
<junit.jupiter.version>5.3.1</junit.jupiter.version>
<mockito.version>2.23.0</mockito.version>
And made a test class:
package com.example.techmagister.sendingemail;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
#ExtendWith({SpringExtension.class, MockitoExtension.class})
#Import(com.example.techmagister.sendingemail.config.FreemarkerConfig.class)
public class EmailTestTest {
private static final Logger LOGGER = LogManager.getLogger(EmailTestTest.class);
#Autowired
#Qualifier("emailConfigBean")
private Configuration emailConfig;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void test() throws Exception {
try {
Template template = emailConfig.getTemplate("email.ftl");
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run that in debug mode, emailConfig is null.
Why is that?
Their test example https://github.com/hdineth/SpringBoot-freemaker-email-send/blob/master/src/test/java/com/example/techmagister/sendingemail/SendingemailApplicationTests.java
works if I add the same autowired property, but it is a full SprintBoot context that is slow to boot, and I need to test just template usage, without actually sending out the email.
In our actual code (which is large, multi module project), I have another error org.springframework.beans.factory.UnsatisfiedDependencyException
caused by:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'freemarker.template.Configuration' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=emailConfigBean)}
But that is just for context, first I want to get it working in the simple, sample project then worry about getting it working in our complex one.
You cannot autowire your emailConfigBean directly as a freemarker.template.Configuration
FreeMarkerConfigurationFactoryBean is a factorybean.
To get the Confuguration you need to call factorybean.getObject()
so instead of
#Autowired
#Qualifier("emailConfigBean")
private Configuration emailConfig;
just autowire your factorybean FreeMarkerConfigurationFactoryBean and load your template with emailConfig.getObject().getTemplate("email.ftl")
#Autowired
#Qualifier("emailConfigBean")
private FreeMarkerConfigurationFactoryBean emailConfig;
#Test
void testFreemarkerTemplate(){
Assertions.assertNotNull(emailConfig);
try {
Template template =
emailConfig
.getObject() // <-- get the configuration
.getTemplate("email.ftl"); // <-- load the template
Assertions.assertNotNull(template);
} catch (Exception e) {
e.printStackTrace();
}
working test on github
On the other hand...
In a Spring Boot application the Freemarker configuration can be simplified by using the spring-boot-starter-freemarker dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
This starter for building MVC web applications using FreeMarker views adds the necessary auto-configuration. All you need to do is placing your template files in the resources/templates folder.
Then you just can autowire the freemarkerConfig (or use constructor injection):
#Autowired
private Configuration freemarkerConfig;
There is a nice example here, in the attached github code. I was able to use it as a starting point to test my freeMarker code: https://cleantestcode.wordpress.com/2014/06/01/unit-testing-freemarker-templates/

Why is PostPersist required to set the id of oneToOne child entity?

I am trying to implement bidirectional OneToOne Mapping and insert child entity(ProjectDetails.java) from parent entity(Project.java). However, entity manager is trying to insert null as id of child entity(ProjectDetails).
Error logs:
[EL Fine]: sql: 2019-08-19 01:16:50.969--ClientSession(1320691525)--Connection(926343068)--INSERT INTO project (name) VALUES (?)
bind => [Project]
[EL Fine]: sql: 2019-08-19 01:16:50.973--ClientSession(1320691525)--Connection(926343068)--SELECT ##IDENTITY
[EL Fine]: sql: 2019-08-19 01:16:50.983--ClientSession(1320691525)--Connection(926343068)--INSERT INTO project_details (project_id, details) VALUES (?, ?)
bind => [null, Details]
[EL Fine]: sql: 2019-08-19 01:16:50.986--ClientSession(1320691525)--SELECT 1
[EL Warning]: 2019-08-19 01:16:50.991--UnitOfWork(1746098804)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: Column 'project_id' cannot be null
Error Code: 1048
I have tried by removing insertable=false, and updatable=false from #OneToOne but it gives me error, that same column can't be referenced twice.
I have following entity classes.
Class : Project
package com.example.playground.domain.dbo;
import com.example.playground.jsonviews.BasicView;
import com.example.playground.jsonviews.ProjectView;
import com.fasterxml.jackson.annotation.JsonView;
import lombok.Data;
import lombok.ToString;
import org.eclipse.persistence.annotations.JoinFetch;
import org.eclipse.persistence.annotations.JoinFetchType;
import javax.persistence.*;
#JsonView(BasicView.class)
#Data
#Entity
#Table(name = "project")
public class Project {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="project_id")
private Integer projectId;
#Column(name="name")
private String name;
#ToString.Exclude
#JsonView(ProjectView.class)
#OneToOne(mappedBy = "project", cascade = CascadeType.ALL, optional = false)
private ProjectDetails projectDetails;
}
Class : ProjectDetails
package com.example.playground.domain.dbo;
import com.example.playground.jsonviews.BasicView;
import com.example.playground.jsonviews.ProjectDetailsView;
import com.fasterxml.jackson.annotation.JsonView;
import lombok.Data;
import lombok.ToString;
import javax.persistence.*;
#JsonView(BasicView.class)
#Data
#Entity
#Table(name = "project_details")
public class ProjectDetails {
#Id
#Column(name = "project_id")
private Integer projectId;
#ToString.Exclude
#JsonView(ProjectDetailsView.class)
#OneToOne
#JoinColumn(name = "project_id", nullable = false, insertable = false, updatable = false)
private Project project;
#Column(name = "details")
private String details;
}
class: ProjectController
package com.example.playground.web;
import com.example.playground.domain.dbo.Project;
import com.example.playground.jsonviews.ProjectView;
import com.example.playground.service.ProjectService;
import com.fasterxml.jackson.annotation.JsonView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("/projects")
public class ProjectController {
#Autowired
private ProjectService projectService;
#GetMapping("/{projectId}")
#JsonView(ProjectView.class)
public ResponseEntity<Project> getProject(#PathVariable Integer projectId){
Project project = projectService.getProject(projectId);
return ResponseEntity.ok(project);
}
#PostMapping
#JsonView(ProjectView.class)
public ResponseEntity<Project> createProject(#RequestBody Project projectDTO){
Project project = projectService.createProject(projectDTO);
return ResponseEntity.ok(project);
}
}
class ProjectService
package com.example.playground.service;
import com.example.playground.domain.dbo.Project;
public interface ProjectService {
Project createProject(Project projectDTO);
Project getProject(Integer projectId);
}
class ProjectServiceImpl
package com.example.playground.impl.service;
import com.example.playground.domain.dbo.Project;
import com.example.playground.repository.ProjectRepository;
import com.example.playground.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class ProjectServiceImpl implements ProjectService {
#Autowired
private ProjectRepository projectRepository;
#Transactional
#Override
public Project createProject(Project projectDTO) {
projectDTO.getProjectDetails().setProject(projectDTO);
return projectRepository.saveAndFlush(projectDTO);
}
#Override
public Project getProject(Integer projectId) {
return projectRepository.findById(projectId).get();
}
}
JPAConfig
package com.example.playground.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
#Configuration
#EnableTransactionManagement(mode= AdviceMode.ASPECTJ)
public class JPAConfig{
#Bean("dataSource")
#ConfigurationProperties(prefix = "db1")
public DataSource getDataSource(){
return DataSourceBuilder.create().build();
}
#Bean("entityManagerFactory")
public LocalContainerEntityManagerFactoryBean getEntityManager(#Qualifier("dataSource") DataSource dataSource){
EclipseLinkJpaVendorAdapter adapter = new EclipseLinkJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPackagesToScan("com.example.playground.domain.dbo");
em.setDataSource(dataSource);
em.setJpaVendorAdapter(adapter);
em.setPersistenceUnitName("persistenceUnit");
em.setJpaPropertyMap(getVendorProperties());
return em;
}
#Bean(name = "transactionManager")
public JpaTransactionManager
transactionManager(#Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory)
{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
protected Map<String, Object> getVendorProperties()
{
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("eclipselink.ddl-generation", "none");
map.put("eclipselink.ddl-generation.output-mode", "database");
map.put("eclipselink.weaving", "static");
map.put("eclipselink.logging.level.sql", "FINE");
map.put("eclipselink.logging.parameters", "true");
map.put(
"eclipselink.target-database",
"org.eclipse.persistence.platform.database.SQLServerPlatform");
return map;
}
}
and pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>playground</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Java-Spring-Boot-Playground</name>
<description>Java playground.</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.7.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jdbc -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>9.0.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Edit : Got it working, but still looking for explaination
If I add below code to my Project class , It works as expected.
#PostPersist
public void fillIds(){
projectDetails.setProjectId(this.projectId);
}
Buy why is postPersist required? Isn't JPA suppose to autofill these values given the relation is marked as oneToOne? Is there any better way?
JPA is following what you instructed it to do: You have two mappings to the "project_id", and the one with a value, the OneToOne is read-only. This means JPA must pull the value from the basic ID mapping 'projectId' which you have left as null, causing it to insert null into the field.
This is a common issue and there are a number of solutions within JPA. First would have been to mark the #ID mapping as read-only (insertable/updatable=false) and let the relationship mapping control the value.
JPA 2.0 brought in other solutions though.
For this same setup, you can mark the relationship with the #MapsId annotation. This tells JPA that the relationship foreign key value is to be used in the specified ID mapping, and will set it for you exactly as you seem to expect without the postPersist method.
Another alternative in JPA 2.0 is that you can just mark the OneToOne as the ID mapping, and remove the projectId property from the class. A more complex example is shown here

Error creating a bean webSecurityConfig through unsatisfied dependency field userDetailsService

I am working on a spring-boot, shopping-cart application.
Everything seems ok, the connection to mysql is working, JDBC is loaded, but i ll always get an exception, i can't find a solution on.
It seems that the Interface UserDetailsService is not properly working. I must say though that i use a deprecated hibernate method Query for Pagination Results. Could this be the reason? Help is appreciated after hours of search. I have no clue 😕Thanks....
Exception:
2018-03-19 18:44:23.192 WARN 10956 --- [main]
ConfigServletWebServerApplicationContext :
Exception encountered during context initialization - cancelling
refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'webSecurityConfig':
Unsatisfied dependency expressed through field 'userDetailsService';
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userDetailsService':
Unsatisfied dependency expressed through field 'accountDAO';
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'accountDAO':
Unsatisfied dependency expressed through field 'sessionFactory';
nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory'
defined in com.maxmaxy.mangoshop.SpringBootMangoShopApplication:
Bean instantiation via factory method failed;
nested exception is
org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.hibernate.SessionFactory]:
Factory method 'getSessionFactory' threw exception;
nested exception is org.hibernate.MappingException:
Failed to scan classpath for unlisted classes
Pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
WebSecurityConfig:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.
AuthenticationManagerBuilder;
import
org.springframework.security.config.annotation.web.builders.
HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.
WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.
BCryptPasswordEncoder;
import com.maxmaxy.mangoshop.service.UserDetailsServiceImpl;
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsServiceImpl userDetailsService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws
Exception {
// Set service to find User in the database & set password encoder
BCryptPasswordEncoder bcryptPasswordEncoder = new
BCryptPasswordEncoder();
auth.userDetailsService(userDetailsService).passwordEncoder
(bcryptPasswordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
//Requires login with role EMPLOYEE or MANAGER. If not, will
redirect to /admin/login
http.authorizeRequests()
.antMatchers("/admin/orderList","/admin/order",
"/admin/accountInfo")
.access("hasAnyRole('ROLE_EMPLOYEE', 'ROLE_MANAGER'");
// Pages only for Manager
http.authorizeRequests().antMatchers("/admin/product")
.access("hasRole('ROLE_MANAGER')");
// When user login, role XX accessDeniedException
http.authorizeRequests().and().exceptionHandling()
.accessDeniedPage("/403");
//Configuration for login form
http.authorizeRequests().and().formLogin()
// Submit the Url
.loginProcessingUrl("/j_spring_security_check")
.loginPage("/admin/login")
.defaultSuccessUrl("/admin/accountInfo")
.failureUrl("/admin/login?error=true")
.usernameParameter("userName")
.passwordParameter("password")
// Configuration for the logout page
.and().logout().logoutUrl("/admin/logout")
.logoutSuccessUrl("/");
}
}
UserDetailsServiceImpl:
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority
.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails
.UserDetailsService;
import org.springframework.security.core.userdetails
.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.maxmaxy.mangoshop.dao.AccountDAO;
import com.maxmaxy.mangoshop.entity.Account;
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private AccountDAO accountDAO;
#Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
Account account = accountDAO.findAccount(username);
System.out.println("Account= " + account);
if (account == null) {
throw new UsernameNotFoundException("User " //
+ username + " was not found in the database");
}
// EMPLOYEE,MANAGER,..
String role = account.getUserRole();
List<GrantedAuthority> grantList =
new ArrayList<GrantedAuthority>();
// ROLE_EMPLOYEE, ROLE_MANAGER
GrantedAuthority authority = new SimpleGrantedAuthority(role);
grantList.add(authority);
boolean enabled = account.isActive();
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
UserDetails userDetails = (UserDetails) new
User(account.getUserName(), //
account.getEncryptedPassword(), enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, grantList);
return userDetails;
}
}
And the last mentioned class in the exception, AccountDAO:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.maxmaxy.mangoshop.entity.Account;
#Transactional
#Repository
public class AccountDAO {
#Autowired
private SessionFactory sessionFactory;
public Account findAccount(String userName) {
Session session = this.sessionFactory.getCurrentSession();
return session.find(Account.class, userName);
}
}
I think it's more easier with spring data you already load it with maven and this is a good step, now you should use it.
don't creat you repository based on session factory but based on spring data like this.
#Repository public interface AccountRepository extends
JpaRepository<AccountEntity, String> {
AccountEntity findByEmail(String username);
AccountEntity findByName(String name);
}
now you can #Autowired it where you want (you don't need any implementations, he understand that AccountEntity is the entity and it have Email and name as an attribute and you need to search by them ^^ )
its well documented if you need any other future

Resources