How to fix org.hibernate.AnnotationException: No identifier specified for entity - spring-boot

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.javacourse.project.hibernateAndJPA.Entities.City
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:609) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.3.jar:5.3.3]
package com.javacourse.project.hibernateAndJPA.Entities;
import javax.persistence.*;
#Entity
#Table(name="city")
public class City {
#Column(name="Id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="name")
private String name;
#Column(name="countryCode")
private String countryCode;
#Column(name="district")
private String district;
#Column(name="population")
private int population;
public City(int id, String name, String countryCode, String district, int population) {
super();
this.id = id;
this.name = name;
this.countryCode = countryCode;
this.district = district;
this.population = population;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}
Application Proporties:
spring.datasource.url=jdbc:derby://localhost:1527/sample
spring.datasource.username=user
spring.datasource.password=1234
spring.datasource.initialize=false
spring.datasource.driver-class-name=org.apache.derby.jdbc.ClientDriver
pom.xml 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.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.javacourse.project</groupId>
<artifactId>hibernateAndJPA</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hibernateAndJPA</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</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.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.derby/derbyclient -->
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.15.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

The #Id annotation is missing
#Id
#Column(name="Id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
Every entity needs an ID aka primary key

Related

Spring Error creating bean with name 'entityManagerFactory'

I am trying to create a custom method for all my repositories and am getting this error. Thank you for your help!
DailyData:
package com.test.demo.Entities;
import javax.persistence.*;
#Entity
#Table(name = "Daily_Data")
public class DailyData {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#Column(name = "Day")
private int time;
#Column(name = "Average_Energy_Value")
private double dailyAvgEnergy_value;
#Column(name = "Maximum_Energy_Value")
private double dailyMaxEnergy_value;
#Column(name = "Minimum_Energy_Value")
private double dailyIdleEnergy_value;
#Column(name = "topics")
private String topics;
}
HourlyData:
package com.test.demo.Entities;
import javax.persistence.*;
#Entity
#Table(name = "HourlyData")
public class HourlyData {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#Column(name = "Hour")
private int time;
#Column(name = "Average_Energy_Value")
private double hourlyAvgEnergy_value;
#Column(name = "Maximum_Energy_Value")
private double hourlyMaxEnergy_value;
#Column(name = "Idle_Energy_Value")
private double hourlyIdleEnergy_value;
#Column(name = "topics")
private String topics;
}
Weekly Data:
package com.test.demo.Entities;
import javax.persistence.*;
import java.sql.Timestamp;
#Entity
#Table(name = "Weekly_Data")
public class WeeklyData {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#Column(name = "Week")
private int time;
#Column(name = "Average_Energy_Value")
private double weeklyAvgEnergy_value;
#Column(name = "Maximum")
private double weeklyMaxEnergy_value;
#Column(name = "Weekly_Data")
private double weeklyIdleEnergy_value;
#Column(name = "Weekly_Data")
private String topics;
}
RawData:
package com.test.demo.Entities;
import javax.persistence.*;
#Entity
#Table(name="Raw_Data")
public class RawData {
//same as in MqttDataModel
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
public Long id;
//TODO:mqttID?
//Same
#Column(name = "timestamp")
public double timestamp;
//Same
#Column(name = "energy_value")
public double energy_value;
//Same
#Column(name="topics")
public String topics;
public String getTopics() {
return topics;
}
public void setTopics(String topics) {
this.topics = topics;
}
public double getEnergy_value() {
return energy_value;
}
public void setEnergy_value(double energy_value) {
this.energy_value = energy_value;
}
public double getTimestamp() {
return timestamp;
}
public void setTimestamp(double timestamp) {
this.timestamp = timestamp;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Generic Repository:
package com.test.demo.GenericRepo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import java.io.Serializable;
import java.util.List;
#NoRepositoryBean
public interface GenericRepository<T,Long extends Serializable> extends JpaRepository<T, Long> {
public List<T> findFromToTimestamp(T t, double beginTime, double endTime);
public List<T> findByTime(T t, double time);
public List<T> findByTopics(T t, List<String> topics);
}
GenericRepositoryImpl:
package com.test.demo.GenericRepo;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.List;
public class GenericRepositoryImpl<T, Long extends Serializable>
extends SimpleJpaRepository<T, Long> implements GenericRepository<T, Long> {
private EntityManager entityManager;
public GenericRepositoryImpl(Class<T> domainClass, EntityManager em) {
super(domainClass, em);
}
#SuppressWarnings("unchecked")
#Transactional
#Override
public List<T> findFromToTimestamp(T t, double beginTime, double endTime) {
return entityManager.createQuery("SELECT * FROM :t WHERE timestamp BETWEEN :begin AND :end").setParameter("t", t.getClass()).setParameter("begin", beginTime).setParameter("end", endTime).getResultList();
}
#SuppressWarnings("unchecked")
#Transactional
#Override
public List<T> findByTime(T t, double time) {
return entityManager.createQuery("SELECT * FROM :t WHERE timestamp like :v").setParameter("t", t.getClass()).setParameter("v", time).getResultList();
}
#SuppressWarnings("unchecked")
#Transactional
#Override
public List<T> findByTopics(T t, List<String> topics) {
return entityManager.createQuery("SELECT * FROM :t WHERE topics like :v").setParameter("t", t.getClass()).setParameter("v", topics.toString()).getResultList();
}
}
RawDataRepository:
package com.test.demo.Repositories;
import com.test.demo.Entities.RawData;
import com.test.demo.GenericRepo.GenericRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface RawDataRepository extends GenericRepository<RawData, Long> {
}
Other repositories and services look the same
DailyDataService:
package com.test.demo.Services;
import com.test.demo.Repositories.DailyDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class DailyDataService {
DailyDataRepository dailyDataRepository;
}
Application:
package com.test.demo;
import com.test.demo.GenericRepo.GenericRepositoryImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories(basePackages = "com.test.demo.Repositories",
repositoryBaseClass = GenericRepositoryImpl.class)
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
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.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>testdb2</name>
<description>demo</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.5.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.5.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Error
log:org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:874) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1344) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:113) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:693) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:510) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:374) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:134) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1707) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1452) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:936) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.23.jar:5.3.23] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.23.jar:5.3.23] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.5.jar:2.7.5] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.5.jar:2.7.5] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.5.jar:2.7.5] at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.5.jar:2.7.5] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.5.jar:2.7.5] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.5.jar:2.7.5] at com.test.demo.TestApplication.main(TestApplication.java:16) ~[classes/:na]
I checked everything again and again, bit I am really not sure what is wrong.
I suspect that the issue is that you are mixing different versions of Spring Boot. Version 3.0.0 and 2.7.5, this leads to a strange mix of dependencies. Your dependency management also defeats te purpose of the parent, which manages all the versions for you. You should remove the version tag from the dependencies you are using.
<?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.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>testdb2</name>
<description>demo</description>
<properties>
<java.version>17</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.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
This cleaned pom will use Spring Boot 2.7.5 dependencies (as declared in the parent). If you want to switch to 3.0.0 just change the version of your parent.
NOTE: When switching to Spring Boot 3.0.0 you need to use the JakartaEE classes (different packages) instead of the JavaEE packages.

Error creating bean with name 'entityManagerFactory' defined in class path Springboot

Tried all possible solutions but can't resolve this error. The application is very basic. I have used MySQLDialect 8 as I use mysql version 8.0.22 but still the error persists. What shall be done to resolve this issue. This is the error that I am getting
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-07-08 20:28:36.746 ERROR 7660 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
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.7.1</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.springrest</groupId>
<artifactId>springrest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springrest</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=8050
#database configuration:mysql
spring.datasource.url=jdbc:mysql://localhost:3306/sampledb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#Hibernate config
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect="org.hibernate.dialect,MySQL8Dialect"
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
Course.java
#Entity
public class Course {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "<seq name in java in generator anno>")
#SequenceGenerator(name = "<seq name in java in generator anno>", sequenceName = "<seq name in db>", allocationSize = 1)
private int id;
private String title;
private String desc;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Course() {
super();
}
public Course(int id, String title, String desc) {
super();
this.id = id;
this.title = title;
this.desc = desc;
}
}
I think you've made a typo and used "," instead of ".".
Try changing "org.hibernate.dialect,MySQL8Dialect" to "org.hibernate.dialect.MySQL8Dialect" in your configuration file.
Check if your database URL is correct and if your database is up and running. Also check if your username and password are correct.

Parse csv file by using Spring Batch and print it on console in spring Boot

My goal of the Project :
I have to read csv file by using Spring Batch and extract the specific column information like (Column Name :"msdin") "msdin" can print it on console. But my application is showing failed to start the application.
Well it is asking me to configure the data Source.Why we need to configure the data source in case of spring batch if my requirement is to read the csv file and print it on console.
I tried to identify the issues but not able to resolve. Can anybody help me how to resolve this issues?
Domain Class
public class Customer implements Serializable {
private Long id_type;
private String id_number;
private String customer_name;
private String email_address;
private LocalDate birthday;
private String citizenship;
private String address;
private Long msisdn;
private LocalDate kyc_date;
private String kyc_level;
private String goalscore;
private String mobile_network;
public Long getId_type() {
return id_type;
}
public void setId_type(Long id_type) {
this.id_type = id_type;
}
public String getId_number() {
return id_number;
}
public void setId_number(String id_number) {
this.id_number = id_number;
}
public String getCustomer_name() {
return customer_name;
}
public void setCustomer_name(String customer_name) {
this.customer_name = customer_name;
}
public String getEmail_address() {
return email_address;
}
public void setEmail_address(String email_address) {
this.email_address = email_address;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public String getCitizenship() {
return citizenship;
}
public void setCitizenship(String citizenship) {
this.citizenship = citizenship;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getMsisdn() {
return msisdn;
}
public void setMsisdn(Long msisdn) {
this.msisdn = msisdn;
}
public LocalDate getKyc_date() {
return kyc_date;
}
public void setKyc_date(LocalDate kyc_date) {
this.kyc_date = kyc_date;
}
public String getKyc_level() {
return kyc_level;
}
public void setKyc_level(String kyc_level) {
this.kyc_level = kyc_level;
}
public String getGoalscore() {
return goalscore;
}
public void setGoalscore(String goalscore) {
this.goalscore = goalscore;
}
public String getMobile_network() {
return mobile_network;
}
public void setMobile_network(String mobile_network) {
this.mobile_network = mobile_network;
}
}
BatchConfiguration class
#Configuration
#EnableBatchProcessing
public class BatchConfiguration {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Value("classPath:/data/gcash.csv")
private Resource inputResource;
public ItemReader<Customer> itemReader() {
FlatFileItemReader<Customer> customerItemReader = new FlatFileItemReader<>();
customerItemReader.setLineMapper(linemapper());
customerItemReader.setLinesToSkip(1);
customerItemReader.setResource(inputResource);
return customerItemReader;
}
#Bean
public LineMapper<Customer> linemapper() {
DefaultLineMapper<Customer> linemapper = new DefaultLineMapper<>();
final DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
tokenizer.setDelimiter(";");
tokenizer.setStrict(false);
tokenizer.setNames(new String[] { "id_type", "id_number", "customer_name", "email_address", "birthday",
"citizenship", "address", "msisdn", "kyc_date", "kyc_level", "goalscore", "mobile_network" });
linemapper.setFieldSetMapper(new BeanWrapperFieldSetMapper<Customer>() {
{
setTargetType(Customer.class);
}
});
return linemapper;
}
}
Error Stack
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-04-27 11:05:46.235 ERROR 22368 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
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.3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.gcash.milo</groupId>
<artifactId>GCash_Milo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GCash_Milo</name>
<description>Developing Milo project for GCash banking application.
</description>
<properties>
<java.version>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-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-sftp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-test</artifactId>
<scope>test</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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>
in your spring boot application class, add the following snippet to #SpringBootApplication annotation:
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
#SpringBootApplcation annotation uses #EnableAutoConfiguration, which expects a datasource to be configured

Error creating bean with name 'dietaController'

So, I have a problem like this:
2020-01-30 22:54:20.059 ERROR 8040 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dietaController': Unsatisfied dependency expressed through field 'dietaRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dietaRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.diet4you.LapkoEkaterina.Entity.Dieta
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>org.diet4you</groupId>
<artifactId>LapkoEkaterina</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My Entity:
#Entity
#Table(name = "diety")
public class Dieta {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="DIETA_ID") private int dietaId;
#NotEmpty
#Column(unique=true, name ="DIETA_NAZWA")
private String nazwa;
#NotEmpty
#Column(name="OPIS") private String opis;
public Dieta(){ }
public Dieta (int dietaId,String nazwa, String opis )
{ this.dietaId = dietaId;
this.nazwa = nazwa;
this.opis = opis; }
public int getDietaId() {
return dietaId; }
public void setDietaId(int dietaId) {
this.dietaId = dietaId; }
public String getNazwa() {
return nazwa; }
public void setNazwa(String nazwa) {
this.nazwa = nazwa; }
public String getOpis() {
return opis; }
public void setOpis(String opis) {
this.opis = opis; }
}
My repository:
#Repository
public interface DietaRepository extends JpaRepository<Dieta, String> {
Dieta findByName (String name);
}
And my Controller:
#RestController
public class DietaController {
#Autowired
private DietaRepository dietaRepository;
#GetMapping("/dieta")
public List<Dieta> getAllNotes() {
return dietaRepository.findAll();
}
}
Application java class:
#Configuration
#SpringBootApplication
#EnableJpaRepositories
#EntityScan ( basePackages = { " com.diet4you.LapkoEkaterina" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
remove space here #EntityScan ( basePackages = { " com.diet4you.LapkoEkaterina" }) between " and com.diet4you...
change extends JpaRepository<Dieta, String> to extends JpaRepository<Dieta, Integer>
remove or fix Dieta findByName (String name) at repository interface, it's mistake

Mockito Test With java.lang.NullPointerException

I created a Spring Boot 2 application with Junit 4 and Mockito. When I test some method. there will be an exception like this :
java.lang.NullPointerException
at com.xxx.service.SurveyServiceTest.getSurveyList(SurveyServiceTest.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Here is my test code
#RunWith(MockitoJUnitRunner.class)
public class SurveyServiceTest {
#MockBean
SurveyRepository repostory;
#InjectMocks
SurveyService service;
#Test
public void getSurveyList() {
when(repostory.findAll()).thenReturn(Arrays.asList( new Survey(new Long(1),101,"Test1"),
new Survey(new Long(2),102,"Test2") ));
assertTrue(service.getSurveyList().size() >0);
}
}
SuveryService.java
#Service
public class SurveyService {
#Autowired
private SurveyRepository repostory;
public List<Survey> getSurveyList() {
return repostory.findAll();
}
public Optional<Survey> getSurveyById() {
return repostory.findById((long) 1);
}
public Survey add() {
Survey survey = new Survey();
survey.setSurveyID(1);
survey.setSurveyContent("ddddd");
return repostory.save(survey);
}
public Survey update() {
Survey survey = new Survey();
survey.setSurveyID(1);
survey.setSurveyContent("gggg1");
return repostory.save(survey);
}
public void delete() {
repostory.deleteById((long) 1);
}
public List<Survey> findBySurveyContent() {
return repostory.findBySurveyContent("gggg1");
}
public int updateBySurveyId(){
return repostory.updateBySurveyId("hhhhhh", 1);
}
}
SurveyRepository.java
public interface SurveyRepository extends JpaRepository<Survey, Long> {
public List<Survey> findBySurveyContent(String surveyContent);
#Query(value = "update XXX_DATA.SURVEYS set SURVEYCONTENT=? where SURVEYID=?",nativeQuery = true)
#Modifying
#Transactional
public int updateBySurveyId(String surveyContent,int surveyId);
}
Survey.java
#Entity
#Table(name="SURVEYS", schema="XXX_DATA")
public class Survey{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Long id;
#Column(name = "SURVEYID")
private Integer surveyID;
#Column(name = "SURVEYCONTENT")
private String surveyContent;
public Survey(){
}
public Survey(Long id,Integer surveyID,String surveyContent){
this.id = id;
this.surveyID = surveyID;
this.surveyContent = surveyContent;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getSurveyID() {
return surveyID;
}
public void setSurveyID(Integer surveyID) {
this.surveyID = surveyID;
}
public String getSurveyContent() {
return surveyContent;
}
public void setSurveyContent(String surveyContent) {
this.surveyContent = surveyContent;
}
}
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.xxx.test</groupId>
<artifactId>xxx-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>xxx-service</name>
<description>XXX Service</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.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>
<repositories>
<repository>
<id>maven-repository</id>
<url>file:///${project.basedir}/maven-repository</url>
</repository>
<repository>
<id>com.ibm.db2.jcc</id>
<url>https://artifacts.alfresco.com/nexus/content/repositories/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.ibm.db2.jcc</groupId>
<artifactId>db2jcc4</artifactId>
<version>10.1</version>
</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-web</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.ibm.watson.developer_cloud</groupId>
<artifactId>java-sdk</artifactId>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.ibm.swat.password</groupId>
<artifactId>cwa2</artifactId>
<version>2.3.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.15</version>
</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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
I referenced this article Mockito NullPointerException, but the issue still existed.
Any help will be appcirated.
#MockBean is a Spring annotation, which only has an effect if you create a Spring boot integration test, run with the SpringRunner.
You have a unit test here, run with MockitoJUnitRunner, and you just want Mockito to create your mock repository. The correct annotation is #Mock.
You sould do that :
#RunWith(MockitoJUnitRunner.class)
public class SurveyServiceTest {
#Mock// and not MockBean
SurveyRepository repostory;
#InjectMocks
SurveyService service;
#Test
public void getSurveyList() {
when(repostory.findAll()).thenReturn(Arrays.asList( new Survey(new Long(1),101,"Test1"),
new Survey(new Long(2),102,"Test2") ));
assertTrue(service.getSurveyList().size() >0);
}
}
To extend the above answers, Since #MockBean is a spring annotation, you can use the below code as an alternative. #MockBean is used to add mock objects to the Spring application context. The mock will replace any existing bean of the same type in the application context. So it is a kind of functionality of both #Mock as well as #InjectMock. Also if you not following JUnit 5 you require to replace #RunWith(SpringRunner.class) with #ExtendWith(SpringExtention.class)
#RunWith(SpringRunner.class)
public class SurveyServiceTest {
#MockBean
SurveyRepository repostory;
#Test
public void getSurveyList() {
when(repostory.findAll()).thenReturn(Arrays.asList( new Survey(new
Long(1),101,"Test1"),
new Survey(new Long(2),102,"Test2") ));
assertTrue(service.getSurveyList().size() >0);
}
}

Resources