Java Spring with H2 Database ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper' - java

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?

Related

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.Unsat

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)

java.net.ConnectException: Connection refused: no further information

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>

Generate a timestamp in a column while inserting in Spring, Hibernate and PostgreSQL

I am learning Spring, Hibernate and PostgreSQL. I have an entity that has the field of the timestamp. A database column of this timestamp is called datecreated.
This timestamp should be generated automatically but is not. While inserting a record, null value is generated only, instead of the date.
I tried many combination of solutions that are on internet, but I not succeeded. I tried this:
#CreationTimestamp
private Date dateCreated;
#CreationTimestamp
#Column
private Date dateCreated;
#CreationTimestamp
#Column
private Date dateCreated = new Date();
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column
private Date dateCreated = new Date();
#Temporal(TemporalType.TIMESTAMP)
#Column
private Date dateCreated = new Date();
#Temporal(TemporalType.TIMESTAMP)
#Column(updatable = false)
private Date dateCreated = new Date();
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(updatable = false)
private Date dateCreated = new Date();
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(updatable = false)
private Date dateCreated;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(updatable = false)
private Date dateCreated;
#PrePersist
protected void onCreate() {
dateCreated = new Date();
}
This is what I am getting:
How to make it generate the timestamps?
Here you are a project files Image.java model, pom.xml, import.sql ddl, hibernate.cfg.xml files:
Image.java
package com.howtodoinjava.demo.spring.domain;
import javax.persistence.*;
import java.util.Date;
import org.hibernate.annotations.CreationTimestamp;
#Entity
#Table(name = "images")
public class Image {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false, length = 300)
private String title;
#Column(nullable = false)
private String url;
#Column(nullable = false)
private String author;
#CreationTimestamp
#Column
private Date dateCreated = new Date();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getDate() {
return dateCreated;
}
public void setDate(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Image() {}
public Image(Long id, String title, String url, String author) {
this.id = id;
this.title = title;
this.url = url;
this.author = author;
}
#Override
public String toString() {
return "Post{" +
"id=" + id +
", title='" + title + '\'' +
", url='" + url + '\'' +
", author=" + author +
", date=" + dateCreated +
'}';
}
}
pom.xml
<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.bitMiners</groupId>
<artifactId>pdf-app</artifactId>
<version>0.0.1</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<aspect.version>1.9.2</aspect.version>
<jackson.version>2.9.8</jackson.version>
<hibernate.version>5.4.2.Final</hibernate.version>
<hibernate.validator.version>6.0.13.Final</hibernate.validator.version>
<c3p0.version>0.9.5.2</c3p0.version>
</properties>
<dependencies>
<!-- servlets and jps -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-extras</artifactId>
<version>3.0.8</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
<exclusion>
<groupId>jboss</groupId>
<artifactId>javassist</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!--hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
<exclusions>
<exclusion>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Hibernate-C3P0 Integration -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<!-- validation -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- for rest services -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<!-- For Aop -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspect.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspect.version}</version>
</dependency>
<!-- To Send Email -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!--logging-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-web -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.13.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.30</version>
</dependency>
<!-- PostgreSQL -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<!-- To define the plugin version in your parent POM -->
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<!-- To use the plugin goals in your POM or parent POM -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</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-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
import.sql
This file is placed in a path: src/main/resources/import.sql and it is automatically executed when running the project. This is taken from a tutorial https://dzone.com/articles/spring-security-5-form-login-with-database-provide
-- ...
INSERT INTO images (title, url, author) VALUES ('lanszaft', 'https://i.imgur.com/sZ64fVI.jpg', 'Oskar KamiƄski');
INSERT INTO images (title, url, author) VALUES ('kobieta w kapeluszu', 'https://i.imgur.com/spMsvHe.png', 'Pablo Picasso');
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.archive.autodetection">class,hbm</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/postgres</property> <!-- BD Mane -->
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.username">user32</property>
<property name="hibernate.connection.password">pa$$word</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL95Dialect</property>
<property name="hibernate.connection.pool.size">1</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<property name="hibernate.jdbc.lob.non_contextual_creation">true</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.max_statements">150</property>
<mapping class="com.howtodoinjava.demo.spring.domain.User"/>
<mapping class="com.howtodoinjava.demo.spring.domain.Authority"/>
<mapping class="com.howtodoinjava.demo.spring.domain.AuthorityType"/>
<mapping class="com.howtodoinjava.demo.spring.domain.Image"/>
</session-factory>
</hibernate-configuration>
The prePersist and other #createTimeStamp hooks works if you are making inserts from within the application by using the JPA or native hibernate methods. If you simply run inserts from outside your application context, there is no way hibernate would come to know what DMLs are running and hence the hooks will never be called. If you want that even from outside when you run the inserts, the timestamp for create should auto populate, you would need to add table level DDL instructions.
Eg: ALTER TABLE mytable ALTER COLUMN datecreated SET DEFAULT now();
Now as to auto DDL ability of hibernate, the xml property <property name="hibernate.hbm2ddl.auto">create</property> generates DDL from entity definitions but not DMLs. So, you can also embed the DEFAULT timestamp value in column definition of the concerned entity as so or similar:
#Column(name="datecreated", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
This will ensure that when the table is created, the definition is applied using the auto DDL property of hibernate settings.
Hope this clarifies
In your image model class, use timestamp
#CreationTimestamp
#Column
private Timestamp timestamp;

I can't find why this error ocured java.lang.IncompatibleClassChangeError: null in spring boot applicaiton

I use spring boot, hibernate, Postgres. I have trouble working with the spring boot project. But I can't figure out what the problem is and when it will come out. Unable to inject my repositories. Does anyone know what I did wrong? In which cases, repository may not be injected.
I'm using spring-boot 2.2.2.RELEASE
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-01-29 11:25:07.089 ERROR 9428 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'blocktestServiceImpl': Unsatisfied dependency expressed through field 'blocktestDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blocktestDao': Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$186/1303239496.getObject(Unknown Source)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
at uz.owl.lmsapp.LmsApp.main(LmsApp.java:20)
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:483)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blocktestDao': Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$186/1303239496.getObject(Unknown Source)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
... 25 common frames omitted
Caused by: java.lang.IncompatibleClassChangeError: null
at org.springframework.data.jpa.util.JpaMetamodel.lambda$isSingleIdAttribute$4(JpaMetamodel.java:94)
at org.springframework.data.jpa.util.JpaMetamodel$$Lambda$707/451217154.test(Unknown Source)
at java.util.Optional.filter(Optional.java:178)
at org.springframework.data.jpa.util.JpaMetamodel.isSingleIdAttribute(JpaMetamodel.java:94)
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl.lambda$new$2(JpaPersistentPropertyImpl.java:110)
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl$$Lambda$697/663202040.get(Unknown Source)
at org.springframework.data.util.Lazy.getNullable(Lazy.java:212)
at org.springframework.data.util.Lazy.get(Lazy.java:94)
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl.isIdProperty(JpaPersistentPropertyImpl.java:141)
at org.springframework.data.jpa.mapping.JpaPersistentEntityImpl.returnPropertyIfBetterIdPropertyCandidateOrNull(JpaPersistentEntityImpl.java:72)
at org.springframework.data.jpa.mapping.JpaPersistentEntityImpl.returnPropertyIfBetterIdPropertyCandidateOrNull(JpaPersistentEntityImpl.java:39)
at org.springframework.data.mapping.model.BasicPersistentEntity.addPersistentProperty(BasicPersistentEntity.java:218)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:538)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:506)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:705)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:374)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator$$Lambda$703/1886151113.accept(Unknown Source)
at java.util.Collections$SingletonSet.forEach(Collections.java:4826)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:548)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:506)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:705)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:374)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator$$Lambda$703/1886151113.accept(Unknown Source)
at java.util.Collections$SingletonSet.forEach(Collections.java:4826)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:548)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:506)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:705)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:374)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:248)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:191)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:85)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$4(RepositoryFactoryBeanSupport.java:295)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport$$Lambda$644/260816667.accept(Unknown Source)
at java.util.Optional.ifPresent(Optional.java:159)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:295)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:121)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792)
... 36 common frames omitted
#Repository
public interface BlocktestDao extends JpaRepository<Blocktest, Long> {
}
#Entity
#Getter
#Setter
#Table(name = "blocktest")
public class Blocktest {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
#OneToMany(mappedBy = "blocktest")
private List<BlocktestSubject> blocktestSubjects = new ArrayList<>();
#OneToMany(mappedBy = "blocktest")
private List<BlocktestGroup> blocktestGroups = new ArrayList<>();
#Override
public String toString() {
return "Blocktest{" +
"id=" + id +
", title='" + title + '\'' +
'}';
}
}
#Service
public class BlocktestServiceImpl implements BlocktestService {
#Autowired private StudentSubjectLevelService priorityService;
#Autowired private BlocktestDao blocktestDao;
#Autowired private StudentGroupDao studentGroupDao;
/**
* Please provide valid student list
* #param students
* #param title
* #return
*/
#Override
#Transactional
public BlocktestDto createBlocktest(List<Student> students, String title) {
return null;
}
}
This is my 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>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>uz.owl</groupId>
<artifactId>LmsApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-envers -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
</dependency>
<!--TODO ===================== SECURITY ===========================-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!--TODO===================<WEB>================-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--TODO=================<DEV TOOL>=================-->
<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>
<!--TODO===========<SPRING DATA POSTGRES>=============-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!--TODO================<TEST DEP>=====================-->
<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>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<!--TODO==============< LOGGING >===================-->
<!-- https://mvnrepository.com/artifact/ch.qos.logback.contrib/logback-mongodb-core -->
<dependency>
<groupId>ch.qos.logback.contrib</groupId>
<artifactId>logback-mongodb-core</artifactId>
<version>0.1.5</version>
</dependency>
<!--TODO===================< POI >=====================-->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
<exclusions>
<exclusion>
<artifactId>org.apache.xmlbeans</artifactId>
<groupId>xmlbeans</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>jboss repo</id>
<name>jboss repo</name>
<url>https://jcenter.bintray.com/</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
UPDATE:
Now I found one more thing. If I delete this relations
#OneToMany(mappedBy = "blocktest")
private List<BlocktestSubject> blocktestSubjects = new ArrayList<>();
#OneToMany(mappedBy = "blocktest")
private List<BlocktestGroup> blocktestGroups = new ArrayList<>();
project can start correctly
This is my other entities:
#Getter
#Setter
#Table(name = Tables.BLOCKTEST_SUBJECT)
public class BlocktestSubject {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "subject_id", nullable = false, insertable = false, updatable = false)
private Long subjectId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "subject_id")
private Subject subject;
#Column(name = "blocktest_id", nullable = false, insertable = false, updatable = false)
private Long blocktestId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "blocktest_id")
private Blocktest blocktest;
#OneToMany(mappedBy = "blocktestSubject", fetch = FetchType.EAGER)
private List<BSPCount> bspCounts;
#OneToMany(mappedBy = "blocktestSubject")
private final List<Rule> rules = new ArrayList<>();
}
#Entity
#Getter
#Setter
public class BlocktestGroup {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "blocktest_id", nullable = false, insertable = false, updatable = false)
private Long blocktestId;
#ManyToOne
#JoinColumn(name = "blocktest_id")
private Blocktest blocktest;
#Column(name = "file_id", insertable = false, updatable = false, nullable = false)
private Long fileId;
#OneToOne
#JoinColumn(name = "file_id")
private TFile tFile;
}
I faced a similar issue while upgrading the spring-boot project from 2.1.1.RELEASE to 2.3.4.RELEASE. I couldn't find any online reference to help.
I tried upgrading my java version from 8 to 15, and the issue got resolved. Try to upgrade your java version and do share if that helps you.

Springboot crud Repository inserting null values

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

Categories