Springboot inserting null values in if i use crud repository even though everything configured correctly and hibernate queries are executing in console but if we check database values for amount and category are inserted as NULL values
Ticket.java
package com.vinay.api.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
#Entity
#Table(name = "Ticket")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#ToString
public class Ticket {
#Id
#GeneratedValue
private int id;
private double amount;
private String category;
}
TicketDao.java
package com.vinay.api.dao;
import org.springframework.data.repository.CrudRepository;
import com.vinay.api.model.Ticket;
public interface TicketDao extends CrudRepository<Ticket, Integer>{
}
TicketController.java
package com.vinay.api.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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.vinay.api.dao.TicketDao;
import com.vinay.api.model.Ticket;
#RestController
#RequestMapping("/tickets")
public class TicketController {
#Autowired
private TicketDao ticketDao;
#PostMapping("/bookTickets")
public String bookTicket(#RequestBody List<Ticket> tickets)
{
ticketDao.saveAll(tickets);
return "tickets booked: "+tickets.size();
}
#GetMapping("/getTickets")
public List<Ticket> getTickets()
{
return (List<Ticket>) ticketDao.findAll();
}
}
SpringMysqlApplication.java
package com.vinay.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMysqlApplication.class, args);
}
}
application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3306/ticket
spring.datasource.username= root
spring.datasource.password=
spring.jpa.show-sql= true
spring.jpa.hibernate.ddl-auto= update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
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.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-mysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mysql</name>
<description>Springboot mysql</description>
<properties>
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I am able to solve this issue i didn't configure lambok in my IDE so i used manual getters and setters removed the #getter and #Setter annotations helped me to solve this issue
Try specifying generation type stretegy.
#GeneratedValue(strategy=GenerationType.AUTO)
Also use wrapper class instead of primitive datatype. Change int to Integer.
private Integer id
Related
I'm new to coding and I was creating a sample springboot application. In get mapping I wanted to display all the items. I'm using JAVAX persistence. but I'm getting an error like
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController' defined in file [C:\Users\TheCanner\Desktop\exchangers\exchangers\target\classes\com\ecommerce\exchangers\controller\HomeController.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'itemServiceImpl' defined in file [C:\Users\TheCanner\Desktop\exchangers\exchangers\target\classes\com\ecommerce\exchangers\Servises\impl\ItemServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'itemsRepo' defined in com.ecommerce.exchangers.repository.ItemsRepo defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.ecommerce.exchangers.entity.Items"
Controller file
package com.ecommerce.exchangers.controller;
import com.ecommerce.exchangers.Servises.ItemService;
import com.ecommerce.exchangers.payload.ItemsDto;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;
#RestController
#RequestMapping("/")
public class HomeController {
private ItemService itemService;
public HomeController(ItemService itemService) {
this.itemService = itemService;
}
#PostMapping("home")
public ResponseEntity<ItemsDto> addItem(#RequestBody ItemsDto itemsDto){
return new ResponseEntity<>(itemService.addItem(itemsDto), HttpStatus.CREATED);
}
}
Entity file
package com.ecommerce.exchangers.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.persistence.*;
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
#EnableJpaRepositories
#Table(name = "Items", uniqueConstraints = { #UniqueConstraint(columnNames = { "itemId" }) })
public class Items {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer itemId;
#Column(name = "Item Category", nullable = false)
private Integer itemPrice;
#Column(name = "Item Category", nullable = false)
private Double itemRating;
#Column(name = "Item Category", nullable = false)
private String itemName;
#Column(name = "Item Category", nullable = false)
private String itemCategory;
}
payload file
package com.ecommerce.exchangers.payload;
import lombok.Data;
#Data
public class ItemsDto {
private int itemId;
private int itemPrice;
private double itemRating;
private String itemName;
private String itemCategory;
}
repository file
package com.ecommerce.exchangers.repository;
import com.ecommerce.exchangers.entity.Items;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ItemsRepo extends JpaRepository<Items,Integer> {
}
service impl file
package com.ecommerce.exchangers.Servises.impl;
import com.ecommerce.exchangers.Servises.ItemService;
import com.ecommerce.exchangers.entity.Items;
import com.ecommerce.exchangers.payload.ItemsDto;
import com.ecommerce.exchangers.repository.ItemsRepo;
import org.springframework.stereotype.Service;
#Service
public class ItemServiceImpl implements ItemService {
private ItemsRepo itemsRepo;
public ItemServiceImpl(ItemsRepo itemsRepo) {
this.itemsRepo = itemsRepo;
}
// Here you have to convert entity into DTO
private ItemsDto mapToDTO(Items items){
ItemsDto itemsDto = new ItemsDto();
itemsDto.setItemId(items.getItemId());
itemsDto.setItemName(items.getItemName());
itemsDto.setItemCategory(items.getItemCategory());
itemsDto.setItemPrice(items.getItemPrice());
itemsDto.setItemRating(items.getItemRating());
return itemsDto;
}
// Here you have to convert entity into DTO
private Items mapToEntity(ItemsDto itemsDto){
Items items = new Items();
items.setItemId(itemsDto.getItemId());
items.setItemName(itemsDto.getItemName());
items.setItemCategory(itemsDto.getItemCategory());
items.setItemPrice(itemsDto.getItemPrice());
items.setItemRating(itemsDto.getItemRating());
return items;
}
#Override
public ItemsDto addItem(ItemsDto itemsDto) {
Items newItem;
newItem = mapToEntity(itemsDto);
Items newItem2 = itemsRepo.save(newItem);
ItemsDto DtoResponse;
DtoResponse = mapToDTO(newItem2);
return DtoResponse;
}
}
Servises file
package com.ecommerce.exchangers.Servises;
import com.ecommerce.exchangers.payload.ItemsDto;
public interface ItemService {
ItemsDto addItem(ItemsDto itemsDto);
}
springBootApplication file
package com.ecommerce.exchangers;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ExchangersApplication {
public static void main(String[] args) {
SpringApplication.run(ExchangersApplication.class, args);
}
}
application.properties file
spring.datasource.url = jdbc:mysql://localhost:3306/ecommproj?useSSL=false&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = root
#hibernate property
#MySQL5InnoDBDialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
#Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
POM
<?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>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ecommerce</groupId>
<artifactId>exchangers</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>exchangers</name>
<description>Demo project using Spring Boot Rest API, MySQL and Kafka (JVM)</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>3.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-http</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-ws</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
errors are like this ( and I also mentioned that above)
I am implementing Spring Data with Redis cache, MySQL, JPA Hibernate CRUD API . Caching is not working for controllers I used and not reflecting but for GetMapping and PostMapping it's working because I am not using any cache configuration, but the other three controllers which I configured with cache, I get connection refused. I didn't install any Redis cache in local. Is it required to install Redis cache for this because I'm using Redis for cache.
Controller
package com.example.redis.springbootrediscache.controller;
import com.example.redis.springbootrediscache.ResouceNotFoundException;
import com.example.redis.springbootrediscache.model.Employee;
import com.example.redis.springbootrediscache.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/api")
public class EmployeeController {
#Autowired
private EmployeeRepository employeeRepository;
#PostMapping("/employees")
public Employee addEmployee(#RequestBody Employee employee) {
return employeeRepository.save(employee);
}
#GetMapping("/employees")
public ResponseEntity<List<Employee>> getAllEmployees() {
return ResponseEntity.ok(employeeRepository.findAll());
}
#GetMapping("employees/{employeeId}")
#Cacheable(value = "employees",key = "#employeeId")
public Employee findEmployeeById(#PathVariable(value = "employeeId") Integer employeeId) {
System.out.println("Employee fetching from database:: "+employeeId);
return employeeRepository.findById(employeeId).orElseThrow(
() -> new ResouceNotFoundException("Employee not found" + employeeId));
}
#PutMapping("employees/{employeeId}")
#CachePut(value = "employees",key = "#employeeId")
public Employee updateEmployee(#PathVariable(value = "employeeId") Integer employeeId,
#RequestBody Employee employeeDetails) {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResouceNotFoundException("Employee not found for this id :: " + employeeId));
employee.setName(employeeDetails.getName());
final Employee updatedEmployee = employeeRepository.save(employee);
return updatedEmployee;
}
#DeleteMapping("employees/{id}")
#CacheEvict(value = "employees", allEntries = true)
public void deleteEmployee(#PathVariable(value = "id") Integer employeeId) {
Employee employee = employeeRepository.findById(employeeId).orElseThrow(
() -> new ResouceNotFoundException("Employee not found" + employeeId));
employeeRepository.delete(employee);
}
}
Employee
package com.example.redis.springbootrediscache.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
public class Employee implements Serializable {
#Id
#GeneratedValue
private int id;
private String name;
}
SpringBootApplication
package com.example.redis.springbootrediscache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
#SpringBootApplication
#EnableCaching
public class SpringbootRedisCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootRedisCacheApplication.class, args);
}
}
application.yaml
spring:
cache:
type: redis
redis:
time-to-live: 60000
cache-null-values: true
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/TradeX
username: postgres
password: admin
hikari:
initialization-fail-timeout: 0
jpa:
database-platform: org.hibernate.dialect.PostgreSQLDialect
generate-ddl: true
show-sql: true
hibernate:
ddl-auto: create
server:
port: 8087
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.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.redis</groupId>
<artifactId>springboot-redis-cache</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-redis-cache</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.5.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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>io.projectreactor</groupId>
<artifactId>reactor-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>
I am using H2 inMemory database for my springboot application.Below is my application.properties content:
spring.datasource.url=jdbc:h2:~/test5
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username= sa
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto= update
spring.h2.console.enabled=true
spring.mvc.format.date-time=iso
server.port=8080
And here below is my entity:
package aero.tav.tams.roster.model;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.tomcat.jni.Local;
import org.hibernate.annotations.Fetch;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
#Entity
#Table(name="Flight")
#Data
#NoArgsConstructor
public class Flight {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(foreignKey= #ForeignKey(name="TKFlight"), name="Airline_id", referencedColumnName = "id")
private Airline airline;
#Column(name="Flight No")
private String flightNo;
#ManyToOne(fetch= FetchType.LAZY)
#JoinColumn(foreignKey = #ForeignKey(name="TKFlightAircraft"), name="Aircraft_id", referencedColumnName = "id")
private Aircraft aircraft;
#Column(name="FlightLeg")
private ArrDepEnum flightLeg;
#Column(name="FlightDate")
private LocalDate flightDate;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(foreignKey = #ForeignKey(name="TKStation"), name="station_id", referencedColumnName = "id")
private Station station;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(foreignKey= #ForeignKey(name="TKOriginStation"), name="OriginStation_id", referencedColumnName = "id")
private Station originStation;
#Column(name="CreTime")
private LocalDateTime creTime;
#Column(name="UpdateTime")
private LocalDateTime updateTime;
#Column(name="UpdateUser")
private String updateUser;
public Flight(
Airline airline,
String flightNo,
Aircraft aircraft,
ArrDepEnum flightLeg,
LocalDate flightDate,
Station station,
Station originStation,
LocalDateTime creTime,
LocalDateTime updateTime) {
this.airline = airline;
this.flightNo = flightNo;
this.aircraft = aircraft;
this.flightLeg = flightLeg;
this.flightDate = flightDate;
this.station = station;
this.originStation = originStation;
this.creTime = creTime;
this.updateTime = updateTime;
}
}
My pom.xml content:
<?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.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>aero.tav.tams</groupId>
<artifactId>roster</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>name</name>
<description>example</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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${project.parent.version}</version>
</plugin>
</plugins>
</build>
</project>
The Errors I get:
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.toString()" because the return value of "springfox.documentation.spi.service.contexts.Orderings.patternsCondition(springfox.documentation.RequestHandler)" is null
Caused by: java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.toString()" because the return value of "springfox.documentation.spi.service.contexts.Orderings.patternsCondition(springfox.documentation.RequestHandler)" is null
What do I do wrong? is it about version problem?
I am creating a Spring Boot project in which I've created a HTML front-end page and I am running a test for it.
I have two basic problems:
Can't find a way to inject MockMvc -> IntelliJ showcases it as error
I am receiving multiple errors, showcased on the following stacktrace.
I don't know if I am missing or I am using some annotations wrong. Can you advise me something?
java.lang.IllegalStateException: Failed to load ApplicationContext at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
at
org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.
test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
at
org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:248)
at
org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
at
org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$8(ClassBasedTestDescriptor.java:363)
at
org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:368)
at
org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$9(ClassBasedTestDescriptor.java:363)
at
java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at
java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
at
java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
at
java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at
java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at
java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
at
java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
at
java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
at
java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
at
org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:362)
at
org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:283)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:282)
at
org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:272)
at java.base/java.util.Optional.orElseGet(Optional.java:364) at
org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:271)
at
org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:102)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:101)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:66)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at
org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at
org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at
org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at
org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at
org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at
org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at
org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at
org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at
com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at
com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at
com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at
com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at
com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'bitPayRatesRepo' defined in
com.andrekreou.iot.bitpay.BitPayRatesRepo defined in
#EnableJpaRepositories declared on IotApplication: Cannot create inner
bean '(inner bean)#6014a9ba' of type
[org.springframework.orm.jpa.SharedEntityManagerCreator] while setting
bean property 'entityManager'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name '(inner bean)#6014a9ba': Cannot resolve
reference to bean 'entityManagerFactory' while setting constructor
argument; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'entityManagerFactory' available at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:389)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:134)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1707)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1452)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:934)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at
org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:132)
at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
... 72 more Caused by:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name '(inner bean)#6014a9ba': Cannot resolve
reference to bean 'entityManagerFactory' while setting constructor
argument; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'entityManagerFactory' available at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:342)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:113)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:693)
at
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:510)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:374)
... 90 more Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'entityManagerFactory' available at
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:872)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1344)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330)
... 98 more
Below I am showcasing my whole project's code.
Home Page Controller Class
package com.andrekreou.iot.bitpay;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class HomePageController {
#GetMapping("/")
public String home(){
return "home";
}
}
HomePageControllerTest
package com.andrekreou.iot;
import com.andrekreou.iot.bitpay.HomePageController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
#WebMvcTest(HomePageController.class)
public class HomePageControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void testHomePage() throws Exception{
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("home"))
.andExpect(content().string(
containsString("Welcome to...")));
}
}
Main Class
package com.andrekreou.iot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories
public class IotApplication {
public static void main(String[] args) {
SpringApplication.run(IotApplication.class, args);
}
}
EntityClass
package com.andrekreou.iot.bitpay;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.time.LocalDateTime;
//This class is responsible for mapping the key variables from
//the JSON array to be imported. The name keys from JSON have
//to be exactly the same as here, in order for data to be fetched.
//Don't forget to apply Lombok, at the end of the project as appendix!!!
#Entity
#Table
#JsonIgnoreProperties(ignoreUnknown = true)
public class BitPayRates {
#Id
#SequenceGenerator(
name = "bitpay_sequence",
sequenceName = "bitpay_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "bitpay_sequence"
)
private Integer id;
private String code;
private String name;
private Long rate;
private java.time.LocalDateTime timestamp;
protected BitPayRates() {
}
public BitPayRates(String code, String name, Long rate, LocalDateTime timestamp) {
this.code = code;
this.name = name;
this.rate = rate;
this.timestamp = timestamp;
}
// Getters and setters
#Override
public String toString() {
return "BitPayRates{" +
"id=" + id +
", code='" + code + '\'' +
", name='" + name + '\'' +
", rate=" + rate +
'}';
}
}
Controller Class
package com.andrekreou.iot.bitpay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
//The controller for the project, which handles HTTP requests
#RestController
public class RestSpringBootController {
//Dependency injection to connect with Service layer
private final Service service;
#Autowired
public RestSpringBootController(Service service) {
this.service = service;
}
#GetMapping(path = "/bitpay")
public List<List<BitPayRates>> getData(){
return service.getData();
}
}
Service Class
package com.andrekreou.iot.bitpay;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Collections;
import java.util.List;
//The service layer class for business logic implementation
#org.springframework.stereotype.Service
public class Service {
//Dependency injection to connect with Repository layer
private final BitPayRatesRepo bitPayRatesRepo;
#Autowired
public Service(BitPayRatesRepo bitPayRatesRepo) {
this.bitPayRatesRepo = bitPayRatesRepo;
}
public List<List<BitPayRates>> getData() {
return Collections.singletonList(bitPayRatesRepo.findAll());
}
}
Repository Interface
package com.andrekreou.iot.bitpay;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
//Interface that multiple classes can use and connects with data JPA
//The JPA is a map that takes the variables mapped in BitPayRates class
//as first parameter and as second, returns the data type of the Id.
#Repository
public interface BitPayRatesRepo
extends JpaRepository<BitPayRates,Integer> {
}
Configuration Class
package com.andrekreou.iot.bitpay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.time.LocalDateTime;
import java.util.List;
//The configuration class to fetch data from url and execute the insertion
//of the data into the PostgreSQL database
#Configuration
public class BitPayRatesConfig {
#Bean
CommandLineRunner commandLineRunner(BitPayRatesRepo bitPayRatesRepo) {
return args -> {
String url = "https://bitpay.com/api/rates";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<BitPayRates>> postEntity = restTemplate.exchange(
url,
HttpMethod.GET,
null,
new ParameterizedTypeReference<>() {
});
List<BitPayRates> results = postEntity.getBody();
bitPayRatesRepo.saveAll(results);
System.out.println(results);
};
}
}
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.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.andrekreou</groupId>
<artifactId>iot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>iot</name>
<description>MSc Thesis</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0-b180830.0359</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I got few microservices and two are running great but on the other two I got some errors. The database schema is not created yet but usually it was created once I started the application successfully. I got similar running classes and I already tried few things such as deleting my repository in .m2 folder which didn't worked out.
I am also using eureka discovery service and eureka zuul.
I am not sure but I think it's not able to find the database schema. When I added a #Entity annotation in another but similar project it failed for the first time.
UPDATE
I figured out that I used the same coloumn name twice in a java class. So the first application is running again. But the second one (similar architecture) doesn't run when I am using annotations such as #Entity or #Column. When I delete them everything is working. The error message is the same.
UPDATE 2
I think it's a logical issue between the following two classes. I am two exhausted right now to figure out tho.
package de.leuphana.jee.component.structure;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class AddressEntity {
private Integer addressId;
private String city;
private String street;
private int zip;
public AddressEntity(String city, String street, int zip)
{
this.city = city;
this.street = street;
this.zip = zip;
}
public AddressEntity() {
}
#Id
#GeneratedValue
public Integer getAddressId() {
return addressId;
}
#Column(name = "city")
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Column(name = "street")
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
#Column(name = "zip")
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
}
package de.leuphana.jee.component.structure;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class OrderEntity {
private Set<AddressEntity> addresses;
private LocalDate orderDate;
private Integer orderId;
private Set<OrderItemEntity> orderItemsEntitySet;
public OrderEntity(AddressEntity addressEntity, LocalDate orderDate) {
addresses = new HashSet<>();
addresses.add(addressEntity);
this.orderDate = orderDate;
orderItemsEntitySet = new HashSet<>();
}
public OrderEntity() {
}
#Id
#GeneratedValue
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public Set<OrderItemEntity> getOrderItemsEntitySet() {
return orderItemsEntitySet;
}
public void setOrderItemsEntitySet(Set<OrderItemEntity> orderItemsEntitySet)
{
this.orderItemsEntitySet = orderItemsEntitySet;
}
public void addOrderItem(OrderItemEntity orderItemEntity) {
orderItemsEntitySet.add(orderItemEntity);
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public Set<AddressEntity> getAddresses() {
return addresses;
}
public void setAddresses(Set<AddressEntity> addresses) {
this.addresses = addresses;
}
public void addAddress(AddressEntity addressEntity) {
addresses.add(addressEntity);
}
}
OLD PROBLEM (pom.xml / application.properties are similar in every project)
Java class:
package de.leuphana.jee.component.structure;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
#Entity
public class CustomerEntity {
// intrinsic attribute
private Integer customerId;
// relational attribute
private CartEntity cartEntity;
#Id
#GeneratedValue
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public CartEntity getCartEntity() {
return cartEntity;
}
public void setCartEntity(CartEntity cartEntity) {
this.cartEntity = cartEntity;
}
}
application.properties:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/shop
spring.datasource.username=shop
spring.datasource.password=shop
server.port=8082
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.springframework</groupId>
<artifactId>customermicroservice</artifactId>
<version>0.1.0</version>
<properties>
<java.version>1.8</java.version>
<docker.image.prefix>microservice</docker.image.prefix>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.M8</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>app</finalName>
<plugins>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<repository>${docker.image.prefix}/${project.artifactId}
</repository>
<buildArgs>
<JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
</buildArgs>
</configuration>
</plugin>
</plugins>
</build>
<!-- brauchen wir die repository? was macht die? -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
Full error message: (sorry for format)
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-03-18 10:14:41.918 ERROR 11928 --- [ 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 javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1085) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:858) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at de.leuphana.jee.Application.main(Application.java:12) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:970) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:895) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:388) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
... 16 common frames omitted
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: de.leuphana.jee.component.structure.CartItemEntity column: article_id (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:835) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:853) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:875) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:607) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.mapping.RootClass.validate(RootClass.java:265) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:459) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
... 23 common frames omitted
SOLVED THE ISSUE
The issue wasn't logical, at least not the way I expected it. I had no setter method for addressId!
Feeling so stupid right now.
My code wasn't able to set a primary key for AddressEntity