Not able to resolve javax.validation.constraints.Email; package - spring

Belo is my whole Entity class code.
package com.email.esp.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "users", uniqueConstraints = { #UniqueConstraint(columnNames = { "email" }) })
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long userId;
#Column(nullable = false, length = 30)
private String name;
#Email(message = "Email is not valid", regexp = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])")
#NotEmpty(message = "Email cannot be empty")
private String email;
#Transient // meaning it will not be saved in DB
//#Size(min = 5, max = 15, message = "{register.password.size}")
private String plainPassword; // unencrytped
#Transient
private String repeatPassword;
#Column(nullable = true)
private String phone;
#Column(nullable = false, length = 500)
private String about;
#Column(nullable = true)
private String profilePic;
#Column(name="enabled")
private Boolean enabled = true;
}
I'm trying to use the spring Email core package in my spring boot project. I have added the dependency in my pom file but for some weird reason the import statement for import javax.validation.constraints.Email; is not getting resolved. Any idea why is this happening?? Here is the dependency , i have ...
<?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.9-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.email</groupId>
<artifactId>esp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>esp</name>
<description>Email Service Provider Using Spring Boot</description>
<properties>
<java.version>17</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

javax.validation.constraints.Email annotation depends on Jakarta Bean Validation providers for validation.
You could try to add spring-boot-starter-validation dependency to your pom.xml. This dependency contains all the required dependencies (including jakarta and hibernate-validator which is a compliant validator for this)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Related

Java Bean Validation API’s #Valid not working (Spring in action)

I am following the book "Spring in Action, 5th Edition". Currently on Chapter 2 where validation is being applied to the forms. I have followed the exact same steps in the book but, but my forms don't recognize that there are any errors.
OrderFromController.java
Using Java Bean Validation API’s #Valid on the Order object being passed into the processOrder method
package com.example.tacocloud.contoller;
import com.example.tacocloud.dto.Order;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import lombok.extern.slf4j.Slf4j;
import javax.validation.Valid;
#Slf4j
#Controller
#RequestMapping("/orders")
public class OrderController {
#GetMapping("/current")
public String orderForm(Model model) {
model.addAttribute("order", new Order());
return "orderForm";
}
#PostMapping
public String processOrder(#Valid Order order, Errors errors) {
if(errors.hasErrors()){
log.info("Handling errors");
return "orderForm";
}
log.info("Order submitted: " + order);
return "redirect:/";
}
}
OrderObject.java
Object on which validation should be performed
package com.example.tacocloud.dto;
import lombok.Data;
import org.hibernate.validator.constraints.CreditCardNumber;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
#Data
public class Order {
#NotBlank(message = "Name is required!")
private String name;
#NotBlank(message="Street is required")
private String street;
#NotBlank(message="City is required")
private String city;
#NotBlank(message="State is required")
private String state;
#NotBlank(message="Zip code is required")
private String zip;
#CreditCardNumber(message = "Not a valid credit card number")
private String ccNumber;
#Pattern(regexp="^(0[1-9]|1[0-2])([\\/])([1-9][0-9])$",
message="Must be formatted MM/YY")
private String ccExpiration;
#Digits(integer=3, fraction=0, message="Invalid CVV")
private String ccCVV;
}
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.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>taco-cloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>taco-cloud</name>
<description>Example from Spring in Action 5th Edition</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.1.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Size Annotation in Spring Boot is returning 400 Bad Request

I am not getting message error while executing #Size annotation in spring boot bean class
below are my files
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.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.val</groupId>
<artifactId>Spring-boot-validation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring-boot-validation</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-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
UserInput.java
package com.val.Springbootvalidation;
import java.time.LocalDate;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#NoArgsConstructor
#AllArgsConstructor
public class UserInput {
#NotNull(message = "lastname can not be null")
#Size(min=3, max= 20, message = "Lastname should be between 3 and 20")
private String lastName;
private String middleName;
private String firstName;
private LocalDate dateOfBirth;
private Integer siblings;
}
User.java
package com.val.Springbootvalidation;
import java.time.LocalDate;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#NoArgsConstructor
#AllArgsConstructor
public class User {
private Long id;
private String lastName;
private String middleName;
private String firstName;
private LocalDate dateOfBirth;
private Integer siblings;
}
SpringBootValidationApplication.java (Main loader)
package com.val.Springbootvalidation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootValidationApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootValidationApplication.class, args);
}
}
Input I am passing is
{
"firstName":"s"
}
Response I am getting is
{
"timestamp": "2020-07-27T07:20:04.655+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/api/user/save"
}
In the console log it is showing
[org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public com.val.Springbootvalidation.User com.val.Springbootvalidation.UserController.save(com.val.Springbootvalidation.UserInput): [Field error in object 'userInput' on field 'lastName': rejected value [null]; codes [NotNull.userInput.lastName,NotNull.lastName,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userInput.lastName,lastName]; arguments []; default message [lastName]]; default message [lastname can not be null]] ]
Spring Boot 2.3.2 has issues with validation messages, or behaviour changed.
Try to downgrade to Spring Boot 2.2.9
Yes, There is issue with Spring 2.3.2 version that Size annotation will not provide proper restful response. After downgrading it to version 2.2.9 it worked as expected. It is returning proper Json with custom error message.

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.

Kotlin SpringBoot and JPA - Problem with relation OneToMany-ManyToOne

I am trying to create a relation OneToMany between two entities and always get an error creating bean with name 'entityManagerFactory':
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-11-23 12:17:20.082 ERROR 17130 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [com.moises.kotlinstoreapi.model.Customer.purchases, com.moises.kotlinstoreapi.model.Purchase.purchasesLines]
...
I have created the same type of relation with other two entities (Customer with Purchase) but in this case it doesn't run...
Product code:
package com.moises.kotlinstoreapi.model
import com.fasterxml.jackson.annotation.JsonManagedReference
import java.time.LocalDateTime
import javax.persistence.*
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotEmpty
import javax.validation.constraints.NotNull
#Entity
#Table(name="products")
data class Product (
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
#NotBlank
val title: String = "",
#NotEmpty
val price: Double = 999.99,
#NotNull
val created_at: LocalDateTime = LocalDateTime.now(),
val update_at: LocalDateTime? = null,
/**
* Relations
*
*/
#OneToOne(mappedBy="product")
val purchaseLine: PurchaseLine? = null
)
Purchase code:
package com.moises.kotlinstoreapi.model
import com.fasterxml.jackson.annotation.JsonBackReference
import com.fasterxml.jackson.annotation.JsonManagedReference
import com.sun.istack.NotNull
import java.time.LocalDateTime
import javax.persistence.*
import javax.validation.constraints.NotEmpty
#Entity
#Table(name="purchases")
data class Purchase(
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private val id: Long=0,
#Column(name="notes", columnDefinition="TEXT")
val notes: String = "",
#NotNull
val created_at: LocalDateTime = LocalDateTime.now(),
val update_at: LocalDateTime? = null,
/**
* Relations
*
*/
//#ManyToOne(cascade = arrayOf(CascadeType.ALL),fetch= FetchType.EAGER)
//#JoinColumn(name="customer_id")
//#JsonBackReference
//val customer: Customer? = null,
#OneToMany(mappedBy="purchase", cascade=arrayOf(CascadeType.ALL), fetch=FetchType.EAGER)
#JsonManagedReference
var purchasesLines: List<PurchaseLine> = emptyList()
)
PurchaseLine code:
package com.moises.kotlinstoreapi.model
import com.fasterxml.jackson.annotation.JsonBackReference
import com.fasterxml.jackson.annotation.JsonManagedReference
import javax.persistence.*
import javax.validation.constraints.NotEmpty
#Entity
#Table(name="purchase_lines")
data class PurchaseLine(
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private val id: Long=0,
#NotEmpty
val quantity: Int = 1,
/**
* Relations
*
*/
#OneToOne(cascade = arrayOf(CascadeType.ALL))
#JoinColumn(name = "product_id")
#JsonManagedReference
val product: Product? = null,
#ManyToOne(cascade = arrayOf(CascadeType.ALL),fetch= FetchType.EAGER)
#JoinColumn(name="purchase_id")
#JsonBackReference
var purchase: Purchase? = null
)
I am usin IntelliJ with Maven and OpenJDK 11 in Ubuntu.
My pow.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.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.moises</groupId>
<artifactId>kotlin-store-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>kotlin-store-api</name>
<description>API store with Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<kotlin.version>1.3.50</kotlin.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-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
<plugin>jpa</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>

Rest template getForObject() mapping only camel case fields

Having a rest web service that returns the below xml response.
Person>
<ttId>1408</ttId>
<FirstName>RAJ</FirstName>
<NationalityValue>INDIAN</NationalityValue>
<Sex>Male</Sex>
</Person>
This is the dto
import java.io.Serializable;
import java.util.Date;
public class PersonInfoDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Long ttId;
private String NationalityValue;
private String Sex;
private String FirstName;
//getters and setters
}
Using Spring Boot, When I try to consume using code it returns only one value(which is in camel case). Do I need to add any Naming strategy to make it work ?
String uri = apiPath;
RestTemplate restTemplate = new RestTemplate();
PersonInfoDto personInfoDto = restTemplate.getForObject(uri, PersonInfoDto.class);
//Here the object will contain only one value
ttId = 1408
rest values are returns null.
Is there any dependency is required for this ?
This is pom file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>msa</groupId>
<artifactId>MQA</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>MQA</name>
<description>MQA project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.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>
<orika-core.version>1.4.6</orika-core.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- Oracle JDBC driver -->
<!-- https://mvnrepository.com/artifact/com.oracle/ojdbc14 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- Orika -->
<dependency>
<groupId>ma.glasnost.orika</groupId>
<artifactId>orika-core</artifactId>
<version>${orika-core.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
You should use #XmlElement. Try this
public class PersonInfoDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Long ttId;
#XmlElement(name = "NationalityValue")
private String nationalityValue;
#XmlElement(name = "Sex")
private String sex;
#XmlElement(name = "FirstName")
private String firstName;
//getters and setters
}
Another option is to write custom Http Message Converter. Have a look at this http://www.baeldung.com/spring-httpmessageconverter-rest
Removed the below entry from the pom.xml. It worked.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Resources