Spring application run failed:UnsatisfiedDependencyException - spring

I'm a beginner in Spring developpement. I've tried to create a web application using Spring boot 2.0.6, but it's giving me the following error:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-10-27 22:58:02.226 ERROR 8536 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.RuntimeException: Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl, jbdc:mysql://localhost:3306/dbutilisateur
Here is my code :
Utilisateur.java (entity):
package org.sid.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Utilisateur implements Serializable {
#Id #GeneratedValue
private Long id;
private boolean is_asso;
private String ref_asso;
private String nom;
private String email;
private String adresse;
private String tel;
private String cin;
private Date dateInscription;
private Date derniereModification;
public Utilisateur(boolean is_asso, String ref_asso, String nom, String email, String adresse, String tel,
String cin, Date dateInscription, Date derniereModification) {
super();
this.is_asso = is_asso;
this.ref_asso = ref_asso;
this.nom = nom;
this.email = email;
this.adresse = adresse;
this.tel = tel;
this.cin = cin;
this.dateInscription = dateInscription;
this.derniereModification = derniereModification;
}
public Utilisateur() {
super();
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public boolean isIs_asso() {
return is_asso;
}
public void setIs_asso(boolean is_asso) {
this.is_asso = is_asso;
}
public String getRef_asso() {
return ref_asso;
}
public void setRef_asso(String ref_asso) {
this.ref_asso = ref_asso;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getCin() {
return cin;
}
public void setCin(String cin) {
this.cin = cin;
}
public Date getDateInscription() {
return dateInscription;
}
public void setDateInscription(Date dateInscription) {
this.dateInscription = dateInscription;
}
public Date getDerniereModification() {
return derniereModification;
}
public void setDerniereModification(Date derniereModification) {
this.derniereModification = derniereModification;
}
}
UtilisateurRepository.java
package org.sid.dao;
import org.sid.entities.Utilisateur;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UtilisateurRepository extends
JpaRepository<Utilisateur,Long> {
}
DemoApplication.java:
package org.sid;
import org.sid.dao.UtilisateurRepository;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.sid.entities.Utilisateur;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoApplication implements CommandLineRunner {
#Autowired
private UtilisateurRepository utilisateurRepository;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
DateFormat df=new SimpleDateFormat("dd/MM/yyyy");
utilisateurRepository.save(new Utilisateur(false,"111","oumaima","sfqs#qsfqs","2mars","09876","BK234",df.parse("12/12/2012"),df.parse("30/12/2012")));
utilisateurRepository.save(new Utilisateur(false,"222","ouma","ouma#qsfqs","3mars","09876","BK234",df.parse("13/12/2012"),df.parse("30/01/2012")));
utilisateurRepository.findAll().forEach(c->{System.out.println(c.getNom());});}}
and application.properties:
spring.datasource.url=jbdc:mysql://localhost:3306/dbutilisateur
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Any suggestion of a solution? Thanks

Is jdbc:mysql ,not jbdc:mysql in your spring configuration
The Word jdbc is wrong

Here is the pom.xml file (default file)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sid</groupId>
<artifactId>utilisateurs </artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

Related

The request resource is not available - Spring, Hibernate, mvn

If we look into the StudentController, request mapping is #RequestMapping("/rest") for class
and get mapping is #GetMapping("/test").
Hence for url http://localhost:8080/TestHibernate/rest/test, I should get a string 'success', which I am not getting.
On executing url http://localhost:8080/TestHibernate I am getting the content placed in index file.
Please let me know what part I am missing.
Thank you.
Controller class
package com.akshay.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.akshay.dao.StudentDAO;
import com.akshay.entity.Student;
#RestController
#RequestMapping("/rest")
public class StudentController {
#Autowired
private StudentDAO studentDAO;
#PostMapping("/saveStudent")
public String save(#RequestBody Student student) {
studentDAO.saveStudent(student);
return "Saved Successfully";
}
#GetMapping("/test")
public String test() {
return "Success";
}
}
DAO Layer
package com.akshay.dao;
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.akshay.entity.Student;
#Repository
#Transactional
public class StudentDAO {
#Autowired
private SessionFactory factory;
private Session getSession() {
Session session = factory.getCurrentSession();
if(session == null) {
session = factory.openSession();
}
return session;
}
public void saveStudent(Student student) {
getSession().save(student);
}
}
Entity Layer
package com.akshay.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
public Student() {
}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
Entry Point
package com.akshay.TestHibernate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TestHibernateApplication {
public static void main(String[] args) {
SpringApplication.run(TestHibernateApplication.class, args);
}
}
POM file
<?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.5.0</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.akshay</groupId>
<artifactId>TestHibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>TestHibernate</name>
<description>Demo project to test hibernate and mysql</description>
<properties>
<java.version>11</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<!--<scope>provided</scope> -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
#
# JDBC connection properties
#
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/web_student_tracker
jdbc.user=springstudent
jdbc.password=springstudent
#
# Connection pool properties
#
connection.pool.initialPoolSize=5
connection.pool.minPoolSize=5
connection.pool.maxPoolSize=20
connection.pool.maxIdleTime=3000
#
# Hibernate properties
#
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.packagesToScan=com.akshay.entity
Introduction
Let's consider the following versions as the current versions:
Spring Boot: 2.7.1.
Analysis
Please, note that the package of the controller class (com.akshay.controller.StudentController) is not the same as the package of the application class (com.akshay.TestHibernate.TestHibernateApplication).
Let's refer to the documentation: Developing with Spring Boot: 6. Using the #SpringBootApplication Annotation:
Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class". A single #SpringBootApplication annotation can be used to enable those three features, that is:
#EnableAutoConfiguration: enable Spring Boot’s auto-configuration mechanism
#ComponentScan: enable #Component scan on the package where the application is located (see the best practices)
#SpringBootConfiguration: enable registration of extra beans in the context or the import of additional configuration classes. An alternative to Spring’s standard #Configuration that aids configuration detection in your integration tests.
Please, note:
#ComponentScan: enable #Component scan on the package where the application is located (see the best practices)
Solution
It is necessary to add the controller package to be component-scanned.
For example:
<…>
#SpringBootApplication
#ComponentScan(basePackages="com.akshay.controller")
public class TestHibernateApplication {
<…>
Test the controller method execution by performing an HTTP request:
curl -X GET http://localhost:8080/rest/test
Additional references
Stack Overflow question. java - Spring Boot: Cannot access REST Controller on localhost (404) - Stack Overflow.

Error creating bean with name 'activityController'

I'm having this problem while running on Server (Tomcat) my project. I have created a Maven project using Spring. The Java version is Java 1.8.
NO SPRING-BOOT!
Error creating bean with name 'activityController': Unsatisfied dependency expressed through field 'activityService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activityService': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.calendar.repository.ActivityDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Could you please help me? Thank you!
This is the code.
Thank you!!!
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.calendar</groupId>
<artifactId>calendar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Calendar</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>5.1.4.RELEASE</springframework.version>
<jackson.version>2.11.2</jackson.version>
<email.version>1.6.2</email.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.0</version>
</dependency>
</dependencies>
<repositories>
</repositories>
<build>
<finalName>company-calendar</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Activity.java
package com.calendar.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.List;
/**
* The persistent class for the activity database table.
*
*/
#Entity
#NamedQuery(name = "Activity.findAll", query = "SELECT a FROM Activity a")
public class Activity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
#Column(name = "create_time")
private Timestamp createTime;
#Column(name = "created_by")
private String createdBy;
private String description;
#Column(name = "update_time")
private Timestamp updateTime;
#Column(name = "updated_by")
private String updatedBy;
//bi-directional many-to-one association to CalendarHeader
#OneToMany(mappedBy = "activity")
private List<CalendarHeader> calendarHeaders;
public Activity() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Timestamp getCreateTime() {
return this.createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
public String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
public List<CalendarHeader> getCalendarHeaders() {
return this.calendarHeaders;
}
public void setCalendarHeaders(List<CalendarHeader> calendarHeaders) {
this.calendarHeaders = calendarHeaders;
}
public CalendarHeader addCalendarHeader(CalendarHeader calendarHeader) {
getCalendarHeaders().add(calendarHeader);
calendarHeader.setActivity(this);
return calendarHeader;
}
public CalendarHeader removeCalendarHeader(CalendarHeader calendarHeader) {
getCalendarHeaders().remove(calendarHeader);
calendarHeader.setActivity(null);
return calendarHeader;
}
}
ActivityDAO.java
package com.calendar.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.calendar.entity.Activity;
#Repository
public interface ActivityDAO extends JpaRepository<Activity, Integer> {}
**ActivityDTO.java**
package com.calendar.dto;
import java.sql.Timestamp;
public class ActivityDTO {
private Integer id;
private String description;
private Timestamp createTime;
private String createdBy;
private Timestamp updateTime;
private String updatedBy;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Timestamp getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
ActivityService.java
package com.calendar.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.calendar.dto.ActivityDTO;
import com.calendar.repository.ActivityDAO;
import com.calendar.entity.Activity;
#Service
public class ActivityService {
#Autowired
ActivityDAO dao;
public List<ActivityDTO> findAll() {
List<ActivityDTO> DTOList = new ArrayList<ActivityDTO>();
List<Activity> entity = dao.findAll();
if (entity != null) {
for (Activity e : entity) {
DTOList.add(getDTOFromEntity(e));
}
}
return DTOList;
};
protected ActivityDTO getDTOFromEntity(Activity entity) {
ActivityDTO activityDTO = new ActivityDTO();
activityDTO.setId(entity.getId());
activityDTO.setDescription(entity.getDescription());
activityDTO.setCreatedBy(entity.getCreatedBy());
activityDTO.setCreateTime(entity.getCreateTime());
activityDTO.setUpdatedBy(entity.getUpdatedBy());
activityDTO.setUpdateTime(entity.getUpdateTime());
return activityDTO;
}
}
ActivityController.java
package com.calendar.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.calendar.dto.ActivityDTO;
import com.calendar.service.ActivityService;
#RestController
#RequestMapping("activity")
public class ActivityController {
#Autowired
private ActivityService activityService;
private ActivityService getService() {
System.out.println("service= " + activityService);
return activityService;
}
#Transactional(readOnly = true)
#GetMapping("")
#ResponseBody
public List<ActivityDTO> findAll() {
System.out.println("SIL findAll");
return getService().findAll();
}
}
AppConfig.java
package com.calendar.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages = "com.calendar")
public class AppConfig implements WebMvcConfigurer {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//to see html files
configurer.enable();
}
//Entity manager
#Bean(name = "Calendar_PU")
public LocalEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("Calendar_PU");
return factoryBean;
}
}
Regards,
Francesco
Try adding #EnableJpaRepositories to your AppConfig:
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "com.calendar.repository")
#ComponentScan(basePackages = "com.calendar")
public class AppConfig implements WebMvcConfigurer {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//to see html files
configurer.enable();
}
//Entity manager
#Bean(name = "Calendar_PU")
public LocalEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("Calendar_PU");
return factoryBean;
}
}
You also need to change your pom.xml. There are too many dependencies (most of them are already part of spring-data-jpa) and spring-data-jpa requires Spring 5.3.5.
<?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.calendar</groupId>
<artifactId>calendar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Calendar</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>5.3.5</springframework.version>
<jackson.version>2.11.2</jackson.version>
<email.version>1.6.2</email.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.0</version>
</dependency>
</dependencies>
<repositories>
</repositories>
<build>
<finalName>company-calendar</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is why you should consider using Spring Boot. You will avoid issues with dependencies that do not work together.

Unable to read configurationProperties

I am trying to use ConfiguartionProperties to read properties from application.prop files. But I am getting NullPointerException because at the time of initiating the bean the properties are not read properly from application.prop file.
#Configuration
#ConfigurationProperties(prefix = "httpool")
public class ClientHttpPoolConfig {
private Integer maxPerRoute;
private Integer maxTotal;
private Integer connectionRequestTimeout;
private Integer connectTimeout;
private Integer socketTimeout;
#Bean
public PoolingHttpClientConnectionManager poolingHttpClntConnMger() {
PoolingHttpClientConnectionManager result = new PoolingHttpClientConnectionManager();
result.setDefaultMaxPerRoute(maxPerRoute); // maxPerRoute is null.
result.setMaxTotal(maxTotal);
return result;
}
}
I simplified as much as I could, so I'm using very simple bean:
StringWrapper
package betlista.springTests.beanInConfiguration;
/** Represents a very simple Bean */
public class StringWrapper {
private String name;
public StringWrapper(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
There is nothing special in configuration class too...
Config
package betlista.springTests.beanInConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
#Component
#ConfigurationProperties
public class Config {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Bean
public StringWrapper getStringWrapper() {
return new StringWrapper(name);
}
}
and finally application
package betlista.springTests.beanInConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {
private static Logger LOG = LoggerFactory.getLogger(SpringBootConsoleApplication.class);
#Autowired
StringWrapper stringWrapper;
public static void main(String[] args) {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
#Override
public void run(String... args) {
LOG.info("stringWrapper.name: {}", stringWrapper.getName());
}
}
Just for completeness
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>betlista</groupId>
<artifactId>springTests-beanInConfiguration</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.2.5.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Prefix
Pretty much same works with #ConfigurationProperties("my") and my.name=Betlista in property file.
All available in GitHub: https://github.com/Betlista/SpringTests/tree/master/BeanInConfiguration
in your application.properties files, parameters should be as follow:
httpool.max-per-route=//here your Integer value
httpool.max-total=//here your Integer value
httpool.connection-requestTimeout=//here your Integer value
httpool.connect-timeout=//here your Integer value
httpool.socket-timeout=//here your Integer value
EDITED:
and you must write this annotation to your Main class
#EnableConfigurationProperties({
ClientHttpPoolConfig.class
})

How to autowire spring-data CrudRepository

A bit of Details
I am having some problem while running the code given below. I am getting the following exception. When i am trying the sample code of [CrudRepository for Spring Data][1].
I have an Interface:
package com.joydeep.springboot;
import org.springframework.data.repository.CrudRepository;
import com.joydeep.springboot.vo.Message;
public interface Test1 extends CrudRepository<Message, String> { }
VO Class:
package com.joydeep.springboot.vo;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Message {
#Id
private String id;
private String text;
private String author;
private Date created;
public Message() {
super();
}
public Message(String id, String text, String author, Date created) {
super();
this.id = id;
this.text = text;
this.author = author;
this.created = created;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
}
Controller class:
package com.joydeep.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloCntrl {
#Autowired
Test1 test;
#RequestMapping("/hello")
public String sayHi(){
return "Hi";
}
}
Initializer class:
package com.joydeep.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class CourseAPIStarter {
public static void main(String[] args) {
SpringApplication.run(CourseAPIStarter.class);
}
}
pom.xml:
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>io.springboot</groupId>
<artifactId>rest-course-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Rest service course API</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
<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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helloCntrl': Unsatisfied dependency expressed through field 'test'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.joydeep.springboot.Test1' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations {#org.springframework.beans.factory.annotation.Autowired(required=true)}
The example i am referring is from this link.
https://spring.io/guides/gs/accessing-data-jpa/
You don't need to put #Repository annotation on Test1. Put these 3 annotation on your CourseAPIStarter class your application will run like hot knife in butter.
#ComponentScan(basePackages={"com.joydeep.springboot"})
#EntityScan(basePackages={"com.joydeep.springboot.vo"})
#EnableJpaRepositories(basePackages={"com.joydeep.springboot"})
#ComponentScan will scan your objects, and will register them with Spring.
#EnableJpaRepositories will enable all your Spring JPA repositories to be used in your application.
#EntityScan: As you added #Entity annotation on your model object class, Spring will assume that a table will exists with name Message. So to register this class with Spring as Entity you need to use this annotation.
Spring can't find Test1 bean because you forgot to annotate it with #Repository. You can autowire only Spring managed classes (Controller, Component, Repository, Service ecc).
Try with this:
#Repository
public interface Test1 extends CrudRepository<Message, String> { }

Spring Boot JPA repository error

i am try using spring boot with hibernate-mysql for learning
i follow the spring boot youtube tutorial and make some change for jpa hibernate-mysql
When run as "spring boot app", it was working fine.
When run as "maven package" on pom.xml, it was failed on "TESTS"
error:
2015-09-18 10:26:19.599 INFO 8328 --- [ main] demo.DemoApplicationTests : Starting DemoApplicationTests on Noir with PID 8328 (D:\eclipse\project\demo\target\test-classes started by Phane in D:\eclipse\project\demo)
2015-09-18 10:26:19.667 INFO 8328 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Refreshing org.springframework.web.context.support.GenericWebApplicationContext#1d0737c8: startup date [Fri Sep 18 10:26:19 SGT 2015]; root of context hierarchy
2015-09-18 10:26:19.768 WARN 8328 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [D:\eclipse\project\demo\target\classes\filmRental\JpaConfig.class]; nested exception is java.lang.annotation.AnnotationFormatError: Invalid default: public abstract java.lang.Class org.springframework.data.jpa.repository.config.EnableJpaRepositories.repositoryBaseClass()
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:303)
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:248)
at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:140)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:266)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:230)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:189)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:270)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:230)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:197)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:166)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:306)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:239)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
this is the java classes:
DemoApplication.java
package demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import filmRental.Staff;
import filmRental.StaffRepository;
import filmRental.StaffServiceImpl;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
#ComponentScan ("filmRental")
#Component
class StaffCommandLineRunner implements CommandLineRunner
{
#Override
public void run(String... arg0) throws Exception
{
for(Staff staff : this.sf.findAll())
{
System.out.println(staff.getStaffID() + " > " + staff.getFirstName());
}
}
#Autowired StaffServiceImpl sf;
}
StaffRestController
package demo;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import filmRental.Staff;
import filmRental.StaffServiceImpl;
#RestController
#ComponentScan ("filmRental")
public class StaffRestController
{
#RequestMapping ("/staff")
public Collection<Staff> listStaff()
{
return sf.findAll();
}
#Autowired StaffServiceImpl sf;
}
StaffServiceImpl.java
package filmRental;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class StaffServiceImpl
{
// #PersistenceContext
// private EntityManager em;
#Resource
private StaffRepository sf;
public List<Staff> findAll()
{
return sf.findAll();
}
}
StaffRepository.java
package filmRental;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
#Transactional
public interface StaffRepository extends JpaRepository<Staff, Byte>{}
Staff.java
package filmRental;
import java.sql.Blob;
import java.sql.Timestamp;
import javax.persistence.*;
#Entity
#Table (name ="Staff")
public class Staff
{
private byte staffID;
private String firstName;
private String lastName;
private byte[] picture;
private String email;
private byte storeID;
private boolean active;
private String userName;
private String password;
private Timestamp lastUpdate;
private Address address;
#Id
#Column (name="staff_id")
public byte getStaffID()
{
return staffID;
}
public void setStaffID(byte staffID)
{
this.staffID = staffID;
}
#Column (name = "first_name")
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
#Column (name = "last_name")
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
#Column (name = "picture", columnDefinition="BLOB")
public byte[] getPicture()
{
return picture;
}
public void setPicture(byte[] picture)
{
this.picture = picture;
}
#Column (name = "email")
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
#Column (name = "store_id")
public byte getStoreID()
{
return storeID;
}
public void setStoreID(byte storeID)
{
this.storeID = storeID;
}
#Column (name = "active")
public boolean getActive()
{
return active;
}
public void setActive(boolean active)
{
this.active = active;
}
#Column (name = "username")
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
#Column (name = "password")
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
#Column (name = "last_update")
public Timestamp getLastUpdate()
{
return lastUpdate;
}
public void setLastUpdate(Timestamp lastUpdate)
{
this.lastUpdate = lastUpdate;
}
#ManyToOne
#JoinColumn(name="address_id")
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
JpaConfig.java
package filmRental;
import java.util.Properties;
import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.hibernate.ejb.HibernatePersistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
#EnableJpaRepositories
public class JpaConfig
{
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);
entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
entityManagerFactoryBean.setJpaProperties(hibProperties());
return entityManagerFactoryBean;
}
private Properties hibProperties()
{
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public JpaTransactionManager transactionManager()
{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
}
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>`enter code here`
<groupId>org.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</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-ws</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Please help, thanks.
You are using Spring Boot then use Spring Boot also the #ComponentScan should go on your application class. (remove it from your command line runner and controller).
#SpringBootApplication
#ComponentScan ({"demo","filmRental"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
#Component
class StaffCommandLineRunner implements CommandLineRunner {
#Autowired StaffServiceImpl sf;
#Override
public void run(String... arg0) throws Exception {
for(Staff staff : this.sf.findAll()) {
System.out.println(staff.getStaffID() + " > " + staff.getFirstName());
}
}
}
Next in your pom remove the spring-data-jpa, hibernate and persistence-api dependencies and replace with spring-boot-starter-data-jpa
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-ws</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-data-jpa</artifactId>
</dependency>
</dependencies>
Now you have dependencies that work together instead of trying to figure out a working combination.
Spring Boot already does auto configuration for you remove your JpaConfig and put the following properties in your application.properties (automatically loaded by Spring Boot!).
spring.datasource.url=<datasource-url>
spring.datasource.driver-class-name=<driver-class-name>
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.jpa.database-platform=<hibernate-dialect>
spring.jpa.show-sql=<show-sql>
For the entity scan use #EntityScan on the application class.
#SpringBootApplication
#ComponentScan ({"demo","filmRental"})
#EntityScan("filmRental")
public class DemoApplication { ... }
Spring Boot now auto configures the DataSource, EntityManagerFactory, transactions, detects Spring Data JPA and enables repositories. I would suggest moving the DemoApplication and everything else in the filmRental package that way you can remove the #ComponentScan and #EntityScan from the DemoApplication.

Resources