JPA cant find Entity meta model even if it is present in code - spring-boot

2018-06-04 16:55:38.821 WARN 10092 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'topicController': Unsatisfied dependency expressed through field 'topicService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'topicService': Unsatisfied dependency expressed through field 'topicRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'topicRepository': Cannot create inner bean '(inner bean)#77e80a5e' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#77e80a5e': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2018-06-04 16:55:38.840 INFO 10092 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-06-04 16:55:38.884 INFO 10092 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-06-04 16:55:39.082 ERROR 10092 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field topicRepository in com.example.demo.topic.TopicService required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
here is my Entity Class
package com.example.demo.topic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Topic")
public class TopicPOJO {
#Id
#Column(name = "Id", nullable = false)
String id;
#Column(name = "name", nullable = true)
String name;
#Column(name = "desc", nullable = true)
String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public TopicPOJO(String id, String name, String description) {
super();
this.id = id;
this.name = name;
this.description = description;
}
public TopicPOJO() {
super();
}
}
**here is my application**
package com.example.demo.topic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoJpaApplication {
public static void main(String[] args) {
SpringApplication.run(DemoJpaApplication.class, args);
}
}
Here is My POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo-JPA</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo-JPA</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
here is my interface which extends repository
package com.example.demo.topic;
import org.springframework.data.repository.CrudRepository;
public interface TopicRepository extends CrudRepository<TopicPOJO,String>
{
}
here is my service class
package com.example.demo.topic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;
#Service
public class TopicService {
#Autowired
TopicRepository topicRepository;
public List<TopicPOJO> getAllTopics()
{
List<TopicPOJO> topics=new ArrayList<>();
topicRepository.findAll()
.forEach(topics::add);
return topics;
}
public TopicPOJO getTopic(String id)
{
return topicRepository.findById(id).get();
}
public void addTopic(TopicPOJO topic)
{
topicRepository.save(topic);
}
public void updateTopic(String id,TopicPOJO topic) {
topicRepository.save(topic);
}
public void deleteTopic(String id) {
topicRepository.deleteById(id);
}
}
Here is my Controller
package com.example.demo.topic;
import java.util.List;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class TopicController {
#Autowired
TopicService topicService;
#RequestMapping("/topic")
public List<TopicPOJO> getAlltopics()
{
return topicService.getAllTopics();
}
#RequestMapping("/topic/{id}")
public TopicPOJO gettopic(#PathVariable String id)
{
return topicService.getTopic(id);
}
#RequestMapping(method=RequestMethod.POST,value="/topic")
public void addTopic(#RequestBody TopicPOJO topic)
{
topicService.addTopic(topic);
}
#RequestMapping(method=RequestMethod.PUT,value="/topic/{id}")
public void updateTopic(#RequestBody TopicPOJO topic,#PathVariable String
id)
{
topicService.updateTopic(id,topic);
}
#RequestMapping(method=RequestMethod.DELETE,value="/topic/{id}")
public void deleteTopic(#PathVariable String id)
{
topicService.deleteTopic(id);
}
}

Related

com.mongodb.MongoSocketOpenException: Exception opening socket with spring boot and mongodb cloud

Please suggest any solution for the below exception which is occuring while running my rest api while executing springboot application with mongodb cloud db. I have created collection in mongodb as well and configured below properties.
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.1.1.jar:na]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:589) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:648) ~[na:na]
at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:78) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.1.1.jar:na]
... 4 common frames omitted
Model class
------------
package com.praveen.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Data;
#Document
public class Products {
#Id
private String id;
private Integer p_id;
private String p_name;
private Integer p_cost;
private Integer countInStock;
private Integer numReviews;
private String image;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getP_id() {
return p_id;
}
public void setP_id(Integer p_id) {
this.p_id = p_id;
}
public String getP_name() {
return p_name;
}
public void setP_name(String p_name) {
this.p_name = p_name;
}
public Integer getP_cost() {
return p_cost;
}
public void setP_cost(Integer p_cost) {
this.p_cost = p_cost;
}
public Integer getCountInStock() {
return countInStock;
}
public void setCountInStock(Integer countInStock) {
this.countInStock = countInStock;
}
public Integer getNumReviews() {
return numReviews;
}
public void setNumReviews(Integer numReviews) {
this.numReviews = numReviews;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Override
public String toString() {
return "Products [id=" + id + ", p_id=" + p_id + ", p_name=" + p_name + ", p_cost=" + p_cost + ", countInStock="
+ countInStock + ", numReviews=" + numReviews + ", image=" + image + "]";
}
}
RestController class
---------------------
package com.praveen.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import com.praveen.entity.Products;
import com.praveen.service.ProductsService;
#RestController
public class ProductsRestController {
#Autowired
private ProductsService service;
#GetMapping("/products")
public ResponseEntity<List<Products>> getProducts(){
List<Products> allProducts = service.getAllProducts();
if(allProducts != null) {
return new ResponseEntity<List<Products>>(allProducts, HttpStatus.OK);
}else {
return new ResponseEntity<List<Products>>(HttpStatus.BAD_REQUEST);
}
}
}
Service class
--------------
package com.praveen.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.praveen.entity.Products;
import com.praveen.repository.ProductsRepository;
#Service
public class ProductsServiceImpl implements ProductsService {
#Autowired
private ProductsRepository prodRepo;
#Override
public List<Products> getAllProducts() {
List<Products> productsList = prodRepo.findAll();
if(productsList != null) {
System.out.println(productsList);
return productsList;
}
return null;
}
}
Repository
-----------
package com.praveen.repository;
import java.io.Serializable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.praveen.entity.Products;
#Repository
public interface ProductsRepository extends MongoRepository<Products, Serializable> {
}
application.properties
-----------------------
spring.data.mongodb.url = mongodb+srv://praveen:praveen#cluster0.qrvkm.mongodb.net/miniproject?retryWrites=true&w=majority
spring.data.mongodb.database = products
spring.data.mongodb.port = 27017
spring.data.mongodb.repositories.enabled=true
pom.xml
-------
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.praveen</groupId>
<artifactId>NgRx-Products</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>05-MiniProject-NgRx-Products</name>
<description>NgRx package with Products data using springboot</description>
<properties>
<java.version>15</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<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>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Please suggest any solution for the above exception, I have given all my files in the above.
Try adding this annotation to your main class file
#EnableAutoConfiguration(exclude={MongoAutoConfiguration.class})
Search services in start.
open it.
search for mongodb there.
start/restart mongodb services from there.
It should work properly.
this exception occurs due to mongodb incorrect port in application properties. So only changing spring.data.mongodb.port=27017 in application.properties file made it work. Also make sure you started mongodb server locally.
Check the connect to MongoDB sever locally with url:portNumber mentioned in the application.properties from where your code is getting executed.

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;
}
}
}
.....................................................

Spring config for connecting to Postgres. Need bean: 'org.flywaydb.core.internal.jdbc.JdbcTemplate'

I'm getting this error when trying to run my Spring application.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-09-22 23:55:45.397 ERROR 36321 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.example.demo.dao.UserDataAccessService required a bean of type 'org.flywaydb.core.internal.jdbc.JdbcTemplate' that could not be found.
Action:
Consider defining a bean of type 'org.flywaydb.core.internal.jdbc.JdbcTemplate' in your configuration.
The application works when I use my fakeUserData file. It seems like there is a dependency issue, but I've double checked and it looks like the dependencies are all there.
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
app:
datasource:
jdbc-url: jdbc:postgresql://localhost:5432/springbootpostgresdb
username: postgres
password: password
pool-size: 30
UserDataAccessService.java
package com.example.demo.dao;
import com.example.demo.model.User;
import org.flywaydb.core.internal.jdbc.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
#Repository("postgresql")
public class UserDataAccessService implements Userdao {
private final JdbcTemplate jdbcTemplate;
#Autowired
public UserDataAccessService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
#Override
public int insertUser(UUID id, User user) {
return 0;
}
#Override
public int deleteUserById(UUID id) {
return 0;
}
#Override
public int updateUserById(UUID id, User user) {
return 0;
}
#Override
public Optional<User> selectUserById(UUID id) {
return Optional.empty();
}
#Override
public List<User> selectAllUsers() {
final String sql = "SELECT id,name FROM userProfile";
try {
return jdbcTemplate.query(sql, (resultSet) -> {
UUID id = UUID.fromString(resultSet.getString("id"));
String name = resultSet.getString("name");
return new User(id, name);
});
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
PostgresDataSource.java
package com.example.demo.datasource;
import com.zaxxer.hikari.HikariDataSource;
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;
#Configuration
public class PostgresDataSource {
#Bean
#ConfigurationProperties("app.datasource")
public HikariDataSource hikariDataSource() {
return DataSourceBuilder
.create()
.type(HikariDataSource.class)
.build();
}
}
Hi I had directly the same problem.
Problem was That when you automatically import library, there are two options.
Flyway or Springframework.
If you import flyway, than you have this problem.
import org.flywaydb.core.internal.jdbc.JdbcTemplate;
If you import spriongwramework everything is OK
import org.springframework.jdbc.core.JdbcTemplate;
I found two problem.
as #stefic said, you should modify your import jdbcTemplate
you should modify your jdbcTemplate query
UserDataAccessService.java
#Override
public List<User> selectAllUsers() {
final String sql = "SELECT id,name FROM userProfile";
return jdbcTemplate.query(sql, (resultSet, i) -> { // <----- add second parameter `i`
UUID id = UUID.fromString(resultSet.getString("id"));
String name = resultSet.getString("name");
return new User(id, name);
});
}

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

UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'

I am trying to connect backend and frontend two separate projects of eclipse spring maven. I have added dependency to do so. But when I write down validate credentials logic in Homecontroller.java, after running on server its showing this exception. Please help to resolve it I have tried many methods already please suggest.
HomeController.java
package com.yogesh.shoponlinefrontend.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.yogesh.shoponlineback.dao.UserDAO;
import com.yogesh.shoponlineback.model.User;
#Controller
public class HomeController {
#Autowired
UserDAO userDAO;
#RequestMapping("/")
public String homePage() {
System.out.println("Executing the method homePage");
return "home";
}
#RequestMapping("/login")
public ModelAndView showLoginPage() {
ModelAndView mv = new ModelAndView("home");
mv.addObject("msg", "You clicked login link");
mv.addObject("showLoginPage", "true");
return mv;
}
#RequestMapping("/register")
public ModelAndView showRegistrationPage() {
ModelAndView mv = new ModelAndView("home");
mv.addObject("msg", "You clicked Registration link ");
mv.addObject("showRegistrationPage", "true");
return mv;
}
#RequestMapping("/validate")
public ModelAndView validate(#RequestParam("id") String id, #RequestParam("password") String pwd) {
System.out.println("In validate method");
System.out.println("id: " + id);
System.out.println("pwd: " + pwd);
ModelAndView mv = new ModelAndView("home");
if (userDAO.validate(id, pwd) != null) {
mv.addObject("successMsg", "You logged in successfully");
} else {
mv.addObject("errorMsg", "Invalid Credentials..Please try again");
}
return mv;
}
}
UserDAO.java
package com.yogesh.shoponlineback.dao;
import java.util.List;
import com.yogesh.shoponlineback.model.User;
public interface UserDAO {
public List<User> list();
public User get(String username);
public User validate(String username, String password);
public boolean save(User user);
public boolean update(User user);
}
User.java
package com.yogesh.shoponlineback.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;
#Entity
//cha
#Table(name="USER")
#Component
public class User {
#Id
private String username;
#NotEmpty(message = "please enter your name")
private String name;
#Min(5)
#Max(15)
private String password;
private String mobile;
private String role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
UserDAOImpl.java
package com.yogesh.shoponlineback.daoimpl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yogesh.shoponlineback.dao.UserDAO;
import com.yogesh.shoponlineback.model.User;
#Service
#Repository()
public class UserDAOImpl implements UserDAO {
#Autowired
UserDAO userDAO;
#Autowired
private SessionFactory sessionFactory;
public UserDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public UserDAOImpl() {
// TODO Auto-generated constructor stub
}
#Transactional
public List<User> list() {
String hql = "from User";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
#Transactional
public User get(String username) {
return (User) sessionFactory.getCurrentSession().get(User.class, username);
}
#Transactional
public User validate(String username, String password) {
String hql = "from User WHERE username ='" + username + "' and password='" + password + "'";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return (User)query.uniqueResult();
}
#Transactional
public boolean save(User user) {
try {
sessionFactory.getCurrentSession().save(user);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
#Transactional
public boolean update(User user) {
try {
sessionFactory.getCurrentSession().update(user);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
:::::::::::::::::::::::::::::Exception trace::::::::::::::::::::::::::::::::::
INFO: FrameworkServlet 'dispatcher': initialization started
Jan 10, 2017 3:19:22 PM **org.springframework.web.context.support.AnnotationConfigWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Jan 10 15:19:22 IST 2017]; root of context hierarchy
Jan 10, 2017 3:19:22 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext loadBeanDefinitions
INFO: Registering annotated classes: [class com.yogesh.shoponlinefrontend.config.AppConfig]
Jan 10, 2017 3:19:23 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Jan 10, 2017 3:19:23 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yogesh.shoponlineback.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Jan 10, 2017 3:19:23 PM org.springframework.web.servlet.DispatcherServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yogesh.shoponlineback.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:592)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
at `enter code here`org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
at** org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4903)
I have updated to this:
#ComponentScan(basePackages = "com.yogesh.shoponlinefrontend,com.yogesh.shoponlineback")
from
#ComponentScan(basePackages = "com.yogesh.shoponlinefrontend)
and it's now working fine.
I had the same problem! My POM file was configured incorrectly.
Check your dependencies (versions).
THis configuration works for me.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.stoliarenko</groupId>
<artifactId>CustomerTracker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- <version>1.0-SNAPSHOT</version>-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<spring.version>5.1.0.RELEASE</spring.version>
<hibernate.version>5.3.5.Final</hibernate.version>
<hibernate.validator>5.4.1.Final</hibernate.validator>
<c3p0.version>0.9.5.2</c3p0.version>
<jstl.version>1.2.1</jstl.version>
<tld.version>1.1.2</tld.version>
<servlets.version>3.1.0</servlets.version>
<jsp.version>2.3.1</jsp.version>
<hsqldb.version>1.8.0.10</hsqldb.version>
</properties>
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.17.Final</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator}</version>
</dependency>
<!-- JSTL Dependency -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${tld.version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlets.version}</version>
<scope>provided</scope>
</dependency>
<!-- JSP Dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>

Resources