Failed to initialize JPA EntityManagerFactory: Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException - spring

I'm working on Spring boot project.
Actually, refactoring code.
And getting this mistake as follows:
Failed to initialize JPA EntityManagerFactory: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: ru.kataproject.p_sm_airlines_1.entity.Document, at table: passenger, for columns: [org.hibernate.mapping.Column(document)]
Any ideas?
Document.java
import lombok.Getter;
import lombok.Setter;
import ru.kataproject.p_sm_airlines_1.util.enums.DocumentType;
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
#Getter
#Setter
#Table(name="document")
public class Document {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "document_gen")
#SequenceGenerator(name = "document_gen", sequenceName = "document_sequence", allocationSize = 1)
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "document_type", nullable = false)
private DocumentType documentType;
#Column(name = "document_number")
private String documentNumber;
#Column(name = "registration_address")
private String registrationAddress;
#Column(name = "where_issued")
private String whereIssued;
#Column(name = "department_code")
private String departmentCode;
#Column(name = "date_of_issue")
private LocalDateTime dateOfIssue;
//todo one to one link to person entity
#Column(name = "person")
private String person = "link to person entity";
}
Passenger.java
import lombok.*;
import javax.persistence.*;
import java.time.LocalDate;
#Getter
#Setter
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Table(name = "passenger", schema = "public")
public class Passenger {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#NonNull
#Column(name="document")
private Document document; // Заглушка , здесь должна быть сущность Document
#NonNull
#Column(name="email")
private String email;
#NonNull
#Column(name="first_name")
private String first_name;
#NonNull
#Column(name="last_name")
private String last_name;
#NonNull
#Column(name="middle_name")
private String middle_name;
#NonNull
#Column(name="date_of_birth")
private LocalDate date_of_birth;
}
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>
<groupId>ru.kataproject</groupId>
<artifactId>airline_project_1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>airline_project_1</name>
<description>Реализуем функционал авиакомпании на базе прототипа</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
<springdoc.openapi.version>1.4.8</springdoc.openapi.version>
<apache-httpcomponents-version>4.5.13</apache-httpcomponents-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${springdoc.openapi.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-data-rest</artifactId>
<version>${springdoc.openapi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${apache-httpcomponents-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.7.4</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.5.0</version>
</dependency>
<dependency>
<groupId>org.thingsboard</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.17.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.17.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.17.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.keycloak.bom</groupId>
<artifactId>keycloak-adapter-bom</artifactId>
<version>12.0.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

You should map entities with #ManyToOne or #OneToOne i.e.
#NonNull
#ManyToOne(fetch = LAZY)
#JoinColumn(name="document")
private Document document;

Related

Error while creating dynamic cloud config using actuator

The controller is InfyGo_Booking to which #RefreshScope is added and also added required dependencies in pom.xml. I have also exposed the endpoints in bootstrap.properties. But still https://localhost:9000/actuator/refresh is giving me 404 error. Can you help me pointing out if I am missing something?
Controller:
#RestController
#RefreshScope
#RequestMapping("/book")
public class BookingController {
protected Logger logger = Logger.getLogger(BookingController.class.getName());
#Autowired
private TicketService ticketService;
#Autowired
private PassengerService passengerService;
private Ticket ticket;
private int noOfSeats;
ClientHttpRequestFactory requestFactory = new
HttpComponentsClientHttpRequestFactory(HttpClients.createDefault());
RestTemplate restTemplate = new RestTemplate(requestFactory);
//
public BookingController() {
ticket = new Ticket();
}
#PostMapping(value = "/{flightId}/{username}", produces = "application/json", consumes = "application/json")
public ResponseEntity<BookingDetails> bookFlight(#PathVariable("flightId") String flightId,
#Valid #RequestBody PassengerDetails passengerDetails, #PathVariable("username") String username,Errors errors) throws InfyGoServiceException, ARSServiceException {
if (errors.hasErrors()) {
return new ResponseEntity(new ClientErrorInformation(HttpStatus.BAD_REQUEST.value(),errors.getFieldError("passengerList").getDefaultMessage()), HttpStatus.BAD_REQUEST);
}
if(passengerDetails.getPassengerList().isEmpty())
throw new InfyGoServiceException(ExceptionConstants.PASSENGER_LIST_EMPTY.toString());
List<Passenger> passengerList = new ArrayList<Passenger>();
for (Passenger passengers : passengerDetails.getPassengerList()) {
passengerList.add(passengers);
}
System.out.println(passengerList.toString());
logger.log(Level.INFO, "Book Flight method ");
logger.log(Level.INFO, passengerDetails.toString());
int pnr = (int) (Math.random() * 1858955);
ticket.setPnr(pnr);
// Date date = new Date();
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(date);
Flight flightDto= restTemplate.getForObject("http://localhost:9004/flights/"+flightId, Flight.class);
double fare= flightDto.getFare();
System.out.println("Fare per person:****** " + fare);
System.out.println("List size:****** " + passengerDetails.getPassengerList().size());
double totalFare = fare * (passengerDetails.getPassengerList().size());
BookingDetails bookingDetails = new BookingDetails();
bookingDetails.setPassengerList(passengerDetails.getPassengerList());
bookingDetails.setPnr(pnr);
bookingDetails.setTotalFare(totalFare);
ticket.setBookingDate(new Date());
System.out.println(ticket.getBookingDate());
ticket.setDepartureDate(flightDto.getFlightAvailableDate());
ticket.setDepartureTime(flightDto.getDepartureTime());
ticket.setFlightId(flightDto.getFlightId());
ticket.setUserId(username);
ticket.setTotalFare(totalFare);
noOfSeats = passengerDetails.getPassengerList().size();
ticket.setNoOfSeats(noOfSeats);
ticketService.createTicket(ticket);
addPassengers(bookingDetails.getPassengerList());
restTemplate.postForEntity("http://localhost:9004/flights/"+flightId+"/"+noOfSeats,null,null);
return new ResponseEntity<BookingDetails>(bookingDetails, HttpStatus.OK);
}
private void addPassengers(List<Passenger> passengers) {
for (Passenger passenger : passengers) {
passenger.setTicket(ticket);
}
passengerService.createPassenger(passengers);
}
}
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</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR5</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
bootstrap.properties:
spring.cloud.config.uri=http://localhost:1111
management.endpoints.web.exposure.include=*
It looks like you are trying to call the actuator as a URL from browser which by default uses GET method . Please try the same URL and hit a post request using any app , you must see a success response .

Spring boot connection with mysql workbecnch

I created a spring boot maven project using STS eclipse
In application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/crud
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.hibernate.ddl-auto = update
I created Player entity class, then I run the project but in my workbench there is no table created. Is that because spring boot not connect with db? Then how can I overcome this problem.
This is my pom.xml
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
This is player Entity
#Entity
#Table(name = "PLAYER")
public class Player {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PLAYER_ID")
private int id;
#Column(name = "PLAYER_NAME")
private String playerName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
}
Maybe you didn't create the Database.
You try to create the database or replace the connection string with the following:
spring.datasource.url = jdbc:mysql://localhost:3306/crud?createDatabaseIfNotExist=true
UPDATE
Please add the following dependency in your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
and delete the following dependency:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>

Error creating bean with name 'entityManagerFactory' error in a Spring boot web application

I'm a beginner in Spring boot coding
When I run my spring boot web application, I got the following error.
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 java.lang.ClassCastException: org.hibernate.mapping.SingleTableSubclass cannot be cast to org.hibernate.mapping.RootClass
I am using STS Eclipse and MySql Database
My Connection string in Application.Properties is
spring.datasource.url=jdbc:mysql://localhost:3306/dreamhospital?zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.main.banner-mode=off
server.port=8100
and this is my pom.xml :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 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.DreamHospital</groupId>
<artifactId>DreamHospital</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>DreamHospital</name>
<description>Demo project for Spring Boot</description>
<properties>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<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-mail</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</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>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
here's my entities class:
this is patient entity:
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#Entity
#DiscriminatorValue("patient")
public class patient implements Serializable{
#Id
private int id;
private String nom;
private String prenom;
#ManyToOne
#JoinColumn(name="idLit")
lit lit;
#ManyToOne
#JoinColumn(name="idM")
medecin medecin;
}
and this is User entity:
#Entity
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="fonction" , discriminatorType=DiscriminatorType.STRING,length=10)
public class User implements Serializable {
#Id
private String UserName;
private String Password;
#Column(name="fonction", insertable = false, updatable = false)
protected String fonction;
and this is medecin entity:
#Data
#Entity
#DiscriminatorValue("medecin")
public class medecin extends User implements Serializable {
#Id #GeneratedValue
private UUID idM;
private String nom;
private String specialite;
#OneToMany(mappedBy="idM")
List<patient> patients;
}
I tried many solutions proposed in stackoverflow but it didn't worked
Apparently there's problem with mappings of User and medecin, you cannot have #Id in superclass and another #Id in subclass. Removing #Id from idM in subclass (medecin) should prevent the exception.

Configure LocaldateTime in Spring Rest API

I use Java 10 with latest Spring spring-boot-starter-parent 2.1.0.RELEASE
POM configuration:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.7</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-poi</artifactId>
<version>1.0.15</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
Rest Endpoint:
#GetMapping("{id}")
public ResponseEntity<?> get(#PathVariable String id) {
return transactionRepository
.findById(Integer.parseInt(id))
.map(mapper::toDTO)
.map(ResponseEntity::ok)
.orElseGet(() -> notFound().build());
}
DTO:
public class PaymentTransactionsDTO {
private Integer id;
private String status;
private LocalDateTime created_at;
private String merchant;
.... getters and setters
}
But when I try to return JSON data for LocalDateTime created_at I get empty result. I suppose that LocalDateTime is not properly converted into JSON value.
Can you advice how I can fix this issue?
JSON serialization is driven by Jackson's ObjectMapper, which I recommend configuring explicitely. For proper serialization of the Java 8 date and time objects, make sure to
register the JavaTimeModule
disable writing dates as timestamps
setting the date format (use StdDateFormat)
Description of StdDateFormat:
Default DateFormat implementation used by standard Date
serializers and deserializers. For serialization defaults to using an
ISO-8601 compliant format (format String "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
and for deserialization, both ISO-8601 and RFC-1123.
Recommended configuration:
#Configuration
public class JacksonConfig {
#Bean
public ObjectMapper objectMapper() {
return new ObjectMapper()
.setAnnotationIntrospector(new JacksonAnnotationIntrospector())
.registerModule(new JavaTimeModule())
.setDateFormat(new StdDateFormat())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
}
}
Examples of serialized date and time objects:
LocalDate: 2018-11-21
LocalTime: 11:13:13.274
LocalDateTime: 2018-11-21T11:13:13.274
ZonedDateTime: 2018-11-21T11:13:13.274+01:00
Edit: standalone dependencies (already included transitively in spring-boot-starter-web):
com.fasterxml.jackson.core:jackson-annotations
com.fasterxml.jackson.core:jackson-databind
com.fasterxml.jackson.datatype:jackson-datatype-jsr310
Try using #JsonFormat on your created_at field.
#JsonFormat(pattern="yyyy-MM-dd")
#DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
private LocalDateTime created_at;
You need to add converter and register in spring eg.
baeldung.com/spring-mvc-custom-data-binder
You can type your PaymentTransactionsDTO "created_at" attribute as a String and use a converter to convert the String to LocalDate (type of the attribute created_at of your entity "PaymentTransactions")
#Component
public class PaymentTransactionsConverter implements Converter<PaymentTransactionsDTO, PaymentTransactions> {
#Override
public PaymentTransactions convert(PaymentTransactionsDTO paymentTransactionsDTO) {
PaymentTransactions paymentTransactions = new PaymentTransactions();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
...
paymentTransactions.setCreated_at(LocalDate.parse(paymentTransactionsDTO.getCreated_at(), formatter));
return paymentTransactions;
}
}
My dates defined as LocalDateTime were been serializaded as an array like this:
"timestamp": [
2023,
2,
15,
10,
30,
45,
732425200
],
So following the Peter Walser answer and using some code of that topic, here is what I did in my WebConfig.java:
#Configuration
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
// other configs
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
WebMvcConfigurer.super.extendMessageConverters(converters);
converters.add(new MappingJackson2HttpMessageConverter(
new Jackson2ObjectMapperBuilder()
.dateFormat(new StdDateFormat())
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build()));
}
}
Now everything is good again:
"timestamp": "2023-02-15T10:32:06.5170689",
Try play around with some Jackson builder properties, hope it's been helpful.

Error creating bean with the name localContainerEntityManagerFactorryBean defined in the class path resource hibernateconfig.class

I'm getting the Error creating bean with the name localContainerEntityManagerFactorryBean defined in the class path resource hibernateconfig.class. nested exception is javax.persistence.persistenceException:unable to build hibernate session factory: A foreign key referring organizer from events has the wrong no of column, should be 2.
My pom file is
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.EventToday</groupId>
<artifactId>EventToday</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>EventToday</name>
<description>projects for events</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<springframework.version>4.0.6.RELEASE</springframework.version>
<hibernate.version>4.3.6.Final</hibernate.version>
<mysql.version>5.1.31</mysql.version>
<joda-time.version>2.3</joda-time.version>
<testng.version>6.9.4</testng.version>
<mockito.version>1.10.19</mockito.version>
<h2.version>1.4.187</h2.version>
<dbunit.version>2.2</dbunit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>ejb3-persistence</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<!-- jsr303 validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.0.2.GA</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<!-- Joda-Time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!-- To map JodaTime with database type -->
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>3.0.0.CR1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>EventToday</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
<compilerArgs>
<arg>-Aopenjpa.metamodel=true</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
</project>
and hibernate configuration
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories("com.EventToday.event.repository")
#ComponentScan({ "com.EventToday.event" })
#PropertySource(value = { "classpath:application.properties" })
public class hibernateconfig {
#Autowired
private Environment environment;
#Bean
public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.MYSQL);
//vendorAdapter.setGenerateDdl(generateDDL);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean beanFactory = new LocalContainerEntityManagerFactoryBean();
beanFactory.setJpaVendorAdapter(vendorAdapter);
beanFactory.setPackagesToScan("com.EventToday.event.model");
beanFactory.setDataSource(dataSource());
//beanFactory.afterPropertiesSet();
beanFactory.setJpaProperties(hibernateProperties());
return beanFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("spring.datasource.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("spring.datasource.url"));
dataSource.setSchema(environment.getRequiredProperty("spring.datasource.schema"));
dataSource.setUsername(environment.getRequiredProperty("spring.datasource.username"));
dataSource.setPassword(environment.getRequiredProperty("spring.datasource.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("spring.jpa.properties.hibernate.dialect", environment.getRequiredProperty("spring.jpa.properties.hibernate.dialect"));
properties.put("spring.jpa.show_sql", environment.getRequiredProperty("spring.jpa.show-sql"));
properties.put("spring.jpa.properties.hibernate.format_sql", environment.getRequiredProperty("spring.jpa.properties.hibernate.format_sql"));
return properties;
}
#Bean
public EntityManagerFactory entityManagerFactory(){
return localContainerEntityManagerFactoryBean().getObject();
}
#Bean
public EntityManager entityManager(){
return entityManagerFactory().createEntityManager();
}
#Bean
PlatformTransactionManager transactionManager(){
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactory());
return manager;
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator(){
return new HibernateExceptionTranslator();
}
}
organizer
#Entity
#Table(name="organizer")
public class Organizer extends BaseEntity{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int roid;
#Column(name="orgNname", nullable=false)
private String organizerName;
#Column(name = "org_contact", nullable = false)
private String orgTelephone;
#Column(name = "org_altcontact", nullable = false)
private String orgContact;
#Column(name = "org_mail_address", nullable = false)
private String mailAddress;
#Column(name = "org_address", nullable = false)
private String orgAddress;
#OneToMany(mappedBy = "organizer")
private Set<events> evts;
public Set<events> getEvts() {
return evts;
}
public void setEvts(Set<events> evts) {
this.evts = evts;
}
public Organizer() {
}
//getters and setters
}
#events
#Entity
#Table(name="event")
public class events extends BaseEntity{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#ManyToOne
#JoinColumn(name = "roid")
private Organizer organizer;
public events() {
}
#Column(name = "event_name", nullable = false)
private String eventname;
#Column(name = "event_date", nullable = false)
#DateTimeFormat(pattern="dd/MM/yyyy")
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate date;
#NotNull
#Digits(integer=8, fraction=2)
#Column(name = "ticket_price", nullable = false)
private BigDecimal price;
#Column(name="event_location", nullable=false)
private String location;
#Column(name="happening_city", nullable=false)
private String Address;
#Column(name="contact_no", nullable=false)
private String contact_no;
#Column(name="alt_contact_no", nullable=false)
private String alternate_contact;
#Column(name="mail_address")
private String mail_address;
//getters and setters
}

Resources