Spring - Failed to convert property value of type java.lang.String to required type - spring

I am making a project of the Housing Association in Spring.
When I'm trying to add an object to my list of apartments I'm getting an error that is written somehow on the page:
https://s28.postimg.org/vrhy6mbd9/blad.jpg
Apartments have relation Many to One Building.
Apartment Controller:
package pl.dmcs.spoldzielnia.controllers;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import pl.dmcs.spoldzielnia.domain.Apartment;
import pl.dmcs.spoldzielnia.service.ApartmentService;
import pl.dmcs.spoldzielnia.service.BuildingService;
#Controller
#SessionAttributes
public class ApartmentController {
#Autowired
ApartmentService apartmentService;
#Autowired
BuildingService buildingService;
#RequestMapping("admin/apartment")
public String listApartment(Map<String, Object> map, HttpServletRequest request) {
int apartmentId = ServletRequestUtils.getIntParameter(request, "apartmentId" , -1);
if (apartmentId > 0)
{
Apartment apartment = apartmentService.getApartment(apartmentId);
apartment.setBuilding(buildingService.getBuilding(apartmentService.getApartment(apartmentId).getBuilding().getId()));
map.put("selectedBuilding", apartmentService.getApartment(apartmentId).getBuilding().getId());
map.put("apartment", apartment);
}
else
map.put("apartment", new Apartment());
map.put("buildingList", buildingService.listBuilding());
map.put("apartmentList", apartmentService.listApartment());
return "apartment";
}
#RequestMapping(value = "admin/addApartment", method = RequestMethod.POST)
public String addContact(#ModelAttribute("apartment") Apartment apartment, BindingResult result,
HttpServletRequest request, Map<String, Object> map) {
if (result.getErrorCount()==0)
{
if (apartment.getId()==0)
{
if (apartment.getBuilding().getId() > 0)
apartment.setBuilding(buildingService.getBuilding(apartment.getBuilding().getId()));
apartmentService.addApartment(apartment);
}
else
{
apartmentService.editApartment(apartment);
}
return "redirect:/admin/apartment.html";
}
map.put("buildingList", buildingService.listBuilding());
map.put("apartmentList", apartmentService.listApartment());
return "apartment";
}
#RequestMapping("admin/delete/apartment/{apartmentId}")
public String deleteApartment(#PathVariable("apartmentId") Integer apartmentId) {
apartmentService.removeApartment(apartmentId);
return "redirect:/admin/apartment.html";
}
// #RequestMapping("/apartment")
// public ModelAndView showContacts() {
//
// return new ModelAndView("apartment", "command", new Apartment());
// }
Domain:
package pl.dmcs.spoldzielnia.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="apartment")
public class Apartment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
int id;
#Column(name="apartmentNumber", nullable=false)
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#ManyToOne
private Building building;
public Building getBuilding() {
return building;
}
public void setBuilding(Building building) {
this.building = building;
}
}
}
Building Service Implementation:
package pl.dmcs.spoldzielnia.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.dmcs.spoldzielnia.dao.BuildingDAO;
import pl.dmcs.spoldzielnia.domain.Building;
import pl.dmcs.spoldzielnia.domain.Building;
#Service
#Transactional
public class BuildingServiceImpl implements BuildingService{
#Autowired
BuildingDAO buildingDAO;
#Transactional
public void addBuilding(Building building) {
buildingDAO.addBuilding(building);
}
#Transactional
public List<Building> listBuilding() {
return buildingDAO.listBuilding();
}
#Transactional
public Building getBuilding(int id) {
return buildingDAO.getBuilding(id);
}
#Transactional
public void removeBuilding(int id) {
buildingDAO.removeBuilding(id);
}
#Transactional
public void editBuilding(Building building) {
buildingDAO.editBuilding(building);
}
}
Could you help me to solve my problem?

The problem is that you are assuming that Spring MVC is going to be able to fill your Apartment object from the data passed. From the form it looks like the Building number is 12, which probably is a unique identifier for the Building in the database, but how is Spring MVC going to know how to go to the database, retrieve the proper building object and put it into the Apartment object?
Remember that objects mapped through SpringMVC parameters are regular Java POJOs, not Hibernate attached entities. So, when the mapping occurs SpringMVC is trying to put "12" into the building attribute of type Building into your POJO (which explains the error you are getting).
You have two options:
First, you can register a custom formatter, that will use the passed id to retrieve a Building from the database:
import org.springframework.core.convert.converter.Converter;
public class BuildingIdToBuildingConverter implements Converter<String, Building> {
private BuildingService buildingService;
public BuildingIdToBuildingConverter(BuildingService buildingService) {
this.buildingService = buildingService;
}
#Override
public Building convert (String id) {
return buildingService.getBuilding(id);
}
}
And register it:
public class AppConfig extends WebMvcConfigurerAdapter {
...
#Bean
public BuildingService buildingService(){
return new BuildingService();
}
#Override
public void addFormatters (FormatterRegistry registry) {
registry.addConverter(new BuildingIdToBuildingConverter(buildingService()));
}
}
Second, do this work manually by sending the building id in a separate parameter:
#RequestMapping(value = "admin/addApartment", method = RequestMethod.POST)
public String addContact(#ModelAttribute("apartment") Apartment apartment, #RequestParam("buildingId") String buildingId, BindingResult result, HttpServletRequest request, Map<String, Object> map) {
if (result.getErrorCount()==0){
if (apartment.getId()==0){
apartment.setBuilding(buildingService.getBuilding(buildingId));
apartmentService.addApartment(apartment);
}
}
else{
apartmentService.editApartment(apartment);
}
return "redirect:/admin/apartment.html";
}
map.put("buildingList", buildingService.listBuilding());
map.put("apartmentList", apartmentService.listApartment());
return "apartment";
}
And change your HTML accordingly to send the buildingId value.

Related

Map/access array inside object on Pojo

How can I access and map an array inside an object on Pojo Spring Boot?
This is what I wanted to map
{
"customers": [
{
"customerId": "0434556574",
"paymentCode": "90501"
}
]
}
You would need to classes to match the JSON structure:
public class CustomersData {
private List<Customer> customers;
// Constructor, getter and setter
}
public class Customer {
private String customerId;
private String paymentCode;
// Constructor, getter and setter
}
Important thing is to make sure your JSON properties name matches the attributes name in your Java classes (thus avoiding explicit mapping between them).
Hi There are lot's of utility libraries you can convert JSON to required java class so that you can instantiate in right way.
Example based on your input:
-----------------------------------com.example.Customer.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"customerId",
"paymentCode"
})
#Generated("jsonschema2pojo")
public class Customer {
#JsonProperty("customerId")
private String customerId;
#JsonProperty("paymentCode")
private String paymentCode;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("customerId")
public String getCustomerId() {
return customerId;
}
#JsonProperty("customerId")
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
#JsonProperty("paymentCode")
public String getPaymentCode() {
return paymentCode;
}
#JsonProperty("paymentCode")
public void setPaymentCode(String paymentCode) {
this.paymentCode = paymentCode;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"customers"
})
#Generated("jsonschema2pojo")
public class Example {
#JsonProperty("customers")
private List<Customer> customers = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("customers")
public List<Customer> getCustomers() {
return customers;
}
#JsonProperty("customers")
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Reference :jsontopojo

How to us a constructor with parameters in a method used by Spring Boot's #RestController annotation to create a request handler

I bought this new book to try to learn Spring Boot quickly. It started out well, and I easily created a REST API. But then we added CrudRepository, and I'm seeing issues with the code as described in the book. Also, there is no code available to download because the author took it down from Oreily's git repo in order to fix some things...
The issue is that if I try to build the code as the book describes (without a default constructor) I get a Java error complaining that there is no default constructor. If I add a default constructor, it builds, but Spring uses it instead of the new constructor, that requires a parameter to be passed. So when I actually call the API, like if I call the /coffees endpoint, I get a java.lang.NullPointerException: null
So how is Spring supposed to know which constructor to use, and how could it pass in values for this parameter?
Here is the controller:
package com.bw.restdemo;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/coffees")
class RestAPIDemoController {
private final CoffeeRepository coffeeRepository;
public RestAPIDemoController(CoffeeRepository coffeeRepository) {
this.coffeeRepository = coffeeRepository;
this.coffeeRepository.saveAll(List.of(
new Coffee("Cafe Cereza"),
new Coffee("Freedom Fuel"),
new Coffee("Cold Brew"),
new Coffee("Sumatra")
));
}
public RestAPIDemoController() {
this.coffeeRepository = null;
};
//#RequestMapping(value = "/coffees", method = RequestMethod.GET)
#GetMapping
Iterable<Coffee> getCoffees() {
return coffeeRepository.findAll();
}
#GetMapping("/{id}")
Optional<Coffee> getCoffeeById(#PathVariable String id) {
return coffeeRepository.findById(id);
}
#PostMapping
Coffee postCoffee(#RequestBody Coffee coffee) {
return coffeeRepository.save(coffee);
}
#PutMapping("/{id}")
ResponseEntity<Coffee> putCoffee(#PathVariable String id, #RequestBody Coffee coffee) {
return (!coffeeRepository.existsById(id))
? new ResponseEntity<>(coffeeRepository.save(coffee), HttpStatus.CREATED)
: new ResponseEntity<>(coffeeRepository.save(coffee), HttpStatus.OK);
}
#DeleteMapping("/{id}")
void deleteCoffee(#PathVariable String id) {
coffeeRepository.deleteById(id);
}
}
Here is where I'm defining the interface:
package com.bw.restdemo;
import org.springframework.data.repository.CrudRepository;
interface CoffeeRepository extends CrudRepository<Coffee, String> {
}
And here's the main class -- apologies for the class stuffed at the bottom.
package com.bw.restdemo;
import java.util.UUID;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class RestDemoApplication {
public static void main(String[] args) {
SpringApplication.run(RestDemoApplication.class, args);
}
}
#Entity
class Coffee {
#Id
private String id;
private String name;
public Coffee(String id, String name) {
this.id = id;
this.name = name;
}
public void setId(String id) {
this.id = id;
}
public Coffee(String name) {
this(UUID.randomUUID().toString(), name);
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
CoffeeRepository interface is missing #Repository Annotation.
Update:
Add #Repository Annotation at CoffeeRepository
Remove the default constructor from RestAPIDemoController.
package com.bw.restdemo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
interface CoffeeRepository extends CrudRepository<Coffee, String> {
}
Explanation
In spring framework, #Component annotation marks a java class as a bean so the component-scanning mechanism can pick it up and pull it into the application context. As #Repository serves as a specialization of #Component , it also enable annotated classes to be discovered and registered with application context.
More at HowToDoInJava - #Repository annotation in Spring Boot

Spring boot - Post function get error while Get and Delete function still be ok

I'm newly get to spring framework and handing-on basic steps however I got a error which didn't where it come from. I just use Postman to communicate with data. Get and delete function were smooth, however Post and Put didn't.
This is my code:
Class EmployeeRepo
package com.employee.demo.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.employee.demo.model.Employee;
public interface EmployeeRepo extends JpaRepository<Employee, Integer>{
}
Class Employee
package com.employee.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Employee {
#Id
private int id;
private String name;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String toString() {
return "Employee with [ID: " + id + ", name: " + name + " and salary: " + salary + "]";
}
}
Class EmployeeController
package com.employee.demo.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.employee.demo.dao.EmployeeRepo;
import com.employee.demo.model.Employee;
#RestController
public class EmployeeController {
#Autowired
EmployeeRepo repo;
#RequestMapping("/")
public String home() {
return "home.jsp";
}
#DeleteMapping("/employee/{id}")
public String deleteEmployee(#PathVariable int id) {
Employee empl = repo.getOne(id);
repo.delete(empl);
return "deleted";
}
#PostMapping("/employee")
public Employee addEmployee(Employee empl) {
repo.save(empl);
return empl;
}
#GetMapping(path = "/employees")
public List<Employee> getEmployees() {
return repo.findAll();
}
#PutMapping(path = "/employee", consumes = {"application/json"})
public Employee saveOrUpdateEmployee(#RequestBody Employee empl) {
repo.save(empl);
return empl;
}
#RequestMapping("/employee/{id}")
public Optional<Employee> getEmployee(#PathVariable int id) {
return repo.findById(id);
}
}
And this is what I got from postman for Post query
Problem is with your POST method (addEmployee)- Whatever you are sending in request body is not accepted by addEmployee method. You can verify in DB after a POST call.
employee table will have data something like
Use #RequestBody annotation with argument as:
public Employee addEmployee(#RequestBody Employee empl)
And it will work as expected.

Spring Boot MongoDB get only certain fields from database into model

I am trying to understand how to work with MongoDB and Spring Boot. I have a mongodb with sample data and I want it to return only selected fields and not the entire data.
My mongoDB collection contains data in the format
DAO.java
package com.books.Reading.DAO;
import com.books.Reading.model.booksModel;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
public interface readingListDAO extends MongoRepository<booksModel, String> {
#Query("{'title' : 'Griffon in Action'}")
public booksModel findFirstByOrderByTitleAsc();
}
model.java
package com.books.Reading.model;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class booksModel {
String title;
String isbn;
int pageCount;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
}
controller.java
package com.books.Reading.controller;
import com.books.Reading.model.booksModel;
import com.books.Reading.service.readingListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class readingListController {
#Autowired
private readingListService rlService;
#RequestMapping("/")
#ResponseBody
public booksModel getOne(){
return rlService.getOne();
}
}
service.java
package com.books.Reading.service;
import com.books.Reading.model.booksModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class readingListService {
#Autowired
private com.books.Reading.DAO.readingListDAO readingListDAO;
public booksModel getOne(){
System.out.println(readingListDAO.findFirstByOrderByTitleAsc());
return readingListDAO.findFirstByOrderByTitleAsc();
}
}
application.properties
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=book
spring.session.mongodb.collection-name=readinglist
The MongoDB is hosted locally. How can I retrieve only selected fields (title, isbn and pageCount) from the database.
I am very new to Spring Boot, so if there are other errors or best practices, I welcome your feedback.
By default, all the properties of document will be fetched. if you want to ignore some of the properties in the result, you can use filter option.
#Query(value = "{'title' : ?0}", fields = "{'description' : 0}")
BooksModel findBooksModelByTitle(String title);

Spring boot (data jpa ) i am not able to save eumn value in database

package com.kk.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#ComponentScan(basePackages="com.kk")
#EnableJpaRepositories(basePackages="com.kk.respositry")
#EntityScan(basePackages="com.kk.entity")
#SpringBootApplication
public class SpringBootEnumExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootEnumExampleApplication.class, args);
}
}
package com.kk.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.kk.entity.Account;
import com.kk.service.AccountService;
#Controller
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value="create",method=RequestMethod.POST)
private #ResponseBody String createAccout(#RequestBody Account account) {
Long l=accountService.save(account);
return "{\"accountId\":l}";
}
}
package com.kk.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.kk.enums.AccountRole;
#Entity
#Table(name = "account_tab")
public class Account {
#Id
#GeneratedValue
private Long id;
private String accountHolderName;
private String mobile;
private Integer age;
#Enumerated(EnumType.STRING)
#Column(name = "account_role", length = 40)
private AccountRole accountRole;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccountHolderName() {
return accountHolderName;
}
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public AccountRole getAccountRole() {
return accountRole;
}
public void setAccountRole(AccountRole accountRole) {
this.accountRole = accountRole;
}
}
package com.kk.enums;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.kk.enums.utils.AccountRoleDeserializer;
#JsonDeserialize(using = AccountRoleDeserializer.class)
public enum AccountRole {
EMPLOYEE_CUSTOMER("Employee customer"),
JOINTER_ACSCOUNT("Jointer customer"),
PRIMARY_ACCOUNT("Primary customer"),
TENANT_ACCOUNT("Tenant customer");
private final String text;
AccountRole(final String text) {
this.text = text;
}
#Override
public String toString() {
return text;
}
public String getText() {
return this.text;
}
public static AccountRole fromText(String text) {
for (AccountRole r : AccountRole.values()) {
if (r.getText().equals(text)) {
return r;
}
}
throw new RuntimeException("Your AccountRole not valied: "+text );
}
}
package com.kk.enums.utils;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.kk.enums.AccountRole;
public class AccountRoleDeserializer extends JsonDeserializer<AccountRole> {
#Override
public AccountRole deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
if (node == null) {
return null;
}
String text = node.textValue(); // gives "A" from the request
if (text == null) {
return null;
}
return AccountRole.fromText(text);
}
}
package com.kk.respositry;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.kk.entity.Account;
#Repository
public interface AccountRespositry extends JpaRepository<Account, Long> {
}
package com.kk.service;
import com.kk.entity.Account;
public interface AccountService {
Long save(Account account);
}
package com.kk.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kk.entity.Account;
import com.kk.respositry.AccountRespositry;
#Service
#Transactional
public class AccountServiceImpl implements AccountService{
#Autowired
private AccountRespositry accountRespositry;
#Override
public Long save(Account account) {
account=accountRespositry.save(account);
return account.getId();
}
}
server.port=8088
server.servlet.context-path=/SpringBootEnum/
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/Account?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
#Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
I am using spring boot (data jpa ) but am getting the wrong value in the database.
The #Enumerated is behaving as expected. It's going to return the name of the enum and that's what gets persisted. Remember JPA uses the name() of the enum and not the toString() even if you have overridden the toString(). I would recommend using an AttributeConverter (JPA 2.1+) to control the persistence of your enum. In your case, create the converter to use the getText() method you already have defined in your Enum.
#Converter(autoApply = true)
public class AccountRoleConverter implements AttributeConverter<AccountRole, String> {
#Override
public String convertToDatabaseColumn(AccountRole role) {
return role.getText();
}
#Override
public AccountRole convertToEntityAttribute(String dbData) {
return AccountRole.fromText(dbData);
}
}
Note: #Converter(autoApply = true), tells JPA provider to use it to map all AccountRole enums.
Now you just need to make sure you remove the #Enumerated from your Account Entity:
#Enumerated(EnumType.STRING)
#Column(name = "account_role", length = 40)
private AccountRole accountRole;
becomes
#Column(name = "account_role", length = 40)
private AccountRole accountRole;
Ok you may ask how you use the converter. Well that is the nice part, you don't have to do anything. The persistence provider will use it for all read and write operations. I hope this helps.

Resources