Working on location based rest api and so far everything is working fine except for one controller with bring this error
2022-03-16 16:28:37.842 WARN 7720 --- [nio-8080-exec-5] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.Producttracking.dto.MetadataDto]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Conflicting setter definitions for property "x": org.postgis.Point#setX(double) vs org.postgis.Point#setX(int)
2022-03-16 16:28:37.847 WARN 7720 --- [nio-8080-exec-5] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.Producttracking.dto.MetadataDto]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Conflicting setter definitions for property "x": org.postgis.Point#setX(double) vs org.postgis.Point#setX(int)
here is the metadata entitty
package com.example.Producttracking.entity;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.n52.jackson.datatype.jts.GeometryDeserializer;
import org.n52.jackson.datatype.jts.GeometrySerializer;
import org.postgis.Point;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalTime;
#Entity
#Table
public class Metadata implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long meta_id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "emp_id", referencedColumnName = "emp_id")
private Employee employee;
private LocalDate date;
private LocalTime time;
#JsonSerialize(using = GeometrySerializer.class)
#JsonDeserialize(contentUsing = GeometryDeserializer.class)
private Point location;
public Metadata() {
}
public Metadata(Long meta_id, Employee employee, LocalDate date, LocalTime time, Point location) {
this.meta_id = meta_id;
this.employee = employee;
this.date = date;
this.time = time;
this.location = location;
}
public Metadata(Employee employee, LocalDate date, LocalTime time, Point location) {
this.employee = employee;
this.date = date;
this.time = time;
this.location = location;
}
public Long getMeta_id() {
return meta_id;
}
public void setMeta_id(Long meta_id) {
this.meta_id = meta_id;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public LocalTime getTime() {
return time;
}
public void setTime(LocalTime time) {
this.time = time;
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
#Override
public String toString() {
return "Metadata{" +
"meta_id=" + meta_id +
", employee=" + employee +
", date=" + date +
", time=" + time +
", location=" + location +
'}';
}
}
here is the the dto
package com.example.Producttracking.dto;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import org.n52.jackson.datatype.jts.GeometryDeserializer;
import org.n52.jackson.datatype.jts.GeometrySerializer;
import org.postgis.Point;
import java.time.LocalDate;
import java.time.LocalTime;
#Data
public class MetadataDto {
private Long emp_id;
private LocalDate date;
private LocalTime time;
#JsonSerialize(using = GeometrySerializer.class)
#JsonDeserialize(contentUsing = GeometryDeserializer.class)
private Point location;
}
here is the controller
package com.example.Producttracking.controller;
import com.example.Producttracking.dto.MetadataDto;
import com.example.Producttracking.entity.Metadata;
import com.example.Producttracking.services.MetadataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping(path = "api/v1/metadata")
public class MetadataController {
private final MetadataService metadataService;
#Autowired
public MetadataController(MetadataService metadataService) {
this.metadataService = metadataService;
}
#GetMapping
public List<Metadata> getMetadata(){
return metadataService.getMetadata();
}
#PostMapping
public void registerMetadata (#RequestBody MetadataDto metadataDto){
metadataService.registerMetadata(metadataDto);
}
}
and here is the service
package com.example.Producttracking.services;
import com.example.Producttracking.dto.MetadataDto;
import com.example.Producttracking.entity.Metadata;
import com.example.Producttracking.repository.MetadataRepository;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
#Service
public class MetadataService {
private final MetadataRepository metadataRepository;
private final ModelMapper modelMapper;
#Autowired
public MetadataService(MetadataRepository metadataRepository, ModelMapper modelMapper) {
this.metadataRepository = metadataRepository;
this.modelMapper = modelMapper;
}
public List<Metadata> getMetadata() {
return metadataRepository.findAll();
}
public void registerMetadata(MetadataDto metadataDto) {
Metadata metadata = modelMapper.map(metadataDto,Metadata.class);
Optional<Metadata> metadataOptional = metadataRepository.findById(metadata.getMeta_id());
if (metadataOptional.isPresent()){
throw new IllegalStateException("metadata exist");
}
metadataRepository.save(metadata);
}
}
Related
So, I'm making an order project, I'm able to create products(id, created_at, deleted, price_in_euros, product_name), and with those products create orders. When I create an order, the products I chose to it become a cartItem(id, amount, productName, product_id, product_name, quantity, order_id). To make this clear, everytime I make an order I create a shoppingCartItem for each product I choose to order. This will saturate my db since if I want to make 2 orders with 30 products each, I'm making 60 different cartItems.
I need to find a way to use a cartItem for different orders if the amount is the same, because 4 cartItems, for example, can be the same product, but with different amounts.
My CloudProduct.java
package com.proj.my.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.sql.Date;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Table;
import jakarta.validation.constraints.Pattern;
#Entity
#Table(name="cloud_product_info")
#SQLDelete(sql = "UPDATE cloud_product_info SET deleted = true WHERE product_id=?")
#Where(clause = "deleted=false")
//#FilterDef(name="", parameters = #ParamDef(name="isDeleted", type = "boolean"))
//#Filter(name="deletedBookFilter", condition = "deleted = :isDeleted")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class CloudProduct {
public static Integer id;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer productId;
#Column(unique=true)
private String productName;
private Float priceInEuros;
#CreationTimestamp
#Column(updatable = false, name = "created_at")
private Date createdAt;
private Boolean deleted = Boolean.FALSE;
#JsonIgnore
public Boolean getdeleted() {
return deleted;
}
#JsonIgnore
public void setdeleted(Boolean deleted) {
this.deleted = deleted;
}
public CloudProduct(Integer productId, String productName, Float priceInEuros) {
this.productId = productId;
this.productName = productName;
this.priceInEuros = priceInEuros;
}
public CloudProduct() {
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Float getpriceInEuros() {
return priceInEuros;
}
public void setProductPrice(Float priceInEuros) {
this.priceInEuros = priceInEuros;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return "Product{" +
"id=" + productId +
", name='" + productName + '\'' +
", price=" + priceInEuros +
'}';
}
}
My Order.java
package com.proj.my.model;
import java.time.LocalDate;
import java.util.List;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import lombok.ToString;
#ToString
#Entity
#Table(name = "myorder")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt"},
allowGetters = true)
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#OneToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "userId")
private User user;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = ShoppingCart.class)
#JoinColumn(name = "order_id")
private List<ShoppingCart> cartItems;
#CreationTimestamp
#Column(updatable = false, name = "createdAt")
private LocalDate createdAt;
public LocalDate getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDate createdAt) {
this.createdAt = createdAt;
}
public Order() {
}
public Order(User user, LocalDate createdAt, List<ShoppingCart> cartItems) {
this.user = user;
this.cartItems = cartItems;
this.createdAt = createdAt;
}
public Order(int Id, LocalDate createdAt, List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
this.createdAt = createdAt;
this.id = Id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setCustomer(User user) {
this.user = user;
}
public List<ShoppingCart> getCartItems() {
return cartItems;
}
public void setCartItems(List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
}
}
My shoppingCart.java
package com.proj.my.model;
import org.hibernate.annotations.NotFound;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
/*#Data
#AllArgsConstructor
#RequiredArgsConstructor
#NoArgsConstructor
*/
#Entity
public class ShoppingCart {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Integer productId;
private String productName;
private int quantity;
private float amount;
public ShoppingCart() {
}
public ShoppingCart(Integer productId, String productName, int quantity, float amount) {
this.productId = productId;
this.productName = productName;
this.quantity = quantity;
this.amount = amount;
}
public ShoppingCart(Integer productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
public ShoppingCart(String productName, int quantity) {
this.productName = productName;
this.quantity = quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
#Override
public String toString() {
return "ShoppingCart{" +
"id=" + id +
", productId=" + productId +
", productName='" + productName + '\'' +
", quantity=" + quantity +
", amount=" + amount +
'}';
}
}
My orderService.java
package com.proj.my.service;
import com.proj.my.model.Order;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.ShoppingCart;
import com.proj.my.repository.OrderRepository;
import com.proj.my.repository.CloudProductRepository;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
#Service
public class OrderService {
private OrderRepository orderRepository;
private CloudProductRepository cloudProductRepository;
public OrderService(OrderRepository orderRepository, CloudProductRepository cloudProductRepository) {
this.orderRepository = orderRepository;
this.cloudProductRepository = cloudProductRepository;
}
public Order getOrderDetail(int orderId) {
Optional<Order> order = this.orderRepository.findById(orderId);
return order.isPresent() ? order.get() : null;
}
public List<Order> getAllOrderDetail(LocalDate dataaa) {
return orderRepository.findAllByCreatedAt(dataaa);
}
public float getCartAmount(List<ShoppingCart> shoppingCartList) {
float totalCartAmount = 0f;
float singleCartAmount = 0f;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()) {
CloudProduct cloudproduct = product.get();
singleCartAmount = cart.getQuantity() * cloudproduct.getpriceInEuros();
totalCartAmount = totalCartAmount + singleCartAmount;
cart.setProductId(cloudproduct.getProductId());
cart.setAmount(singleCartAmount);
cloudProductRepository.save(cloudproduct);
}
}
return totalCartAmount;
}
public Order saveOrder(Order order) {
return orderRepository.save(order);
}
}
My orderController.java
package com.proj.my.controller;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.dto.OrderDTO;
import com.proj.my.dto.ResponseOrderDTO;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.Order;
import com.proj.my.model.ShoppingCart;
import com.proj.my.model.User;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;
import com.proj.my.service.OrderService;
import com.proj.my.service.UserService;
#RestController
#RequestMapping("/api")
public class OrderController {
private OrderService orderService;
private CloudProductService cloudProductService;
private UserService userService;
#Autowired
private CloudProductRepository cloudProductRepository;
public OrderController(OrderService orderService, CloudProductService cloudProductService, UserService userService) {
this.orderService = orderService;
this.cloudProductService = cloudProductService;
this.userService = userService;
}
#GetMapping(value = "/getOrder/{orderId}")
public ResponseEntity<Order> getOrderDetails(#PathVariable int orderId) {
Order order = orderService.getOrderDetail(orderId);
return ResponseEntity.ok(order);
}
#GetMapping(value = "/getOrders/{dataaa}")
public List<Order> getAllOrderDetails(#PathVariable LocalDate dataaa) {
return orderService.getAllOrderDetail(dataaa);
}
#PostMapping("/placeOrder")
public ResponseEntity<?> placeOrder(#RequestBody OrderDTO orderDTO) {
ResponseOrderDTO responseOrderDTO = new ResponseOrderDTO();
List<ShoppingCart> shoppingCartList = orderDTO.getCartItems();
ShoppingCart shoppingCart;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()){
float amount = orderService.getCartAmount(orderDTO.getCartItems());
if(amount > 0){
User user = new User(orderDTO.getuserEmail());
Integer userIdFromDb = userService.isUserPresent(user);
if (userIdFromDb != null) {
user.setUserId(userIdFromDb);
}else{
user = userService.createUser(user);
}
LocalDate createdAt = LocalDate.now();
Order order = new Order(user, createdAt, orderDTO.getCartItems());
order = orderService.saveOrder(order);
responseOrderDTO.setAmount(amount);
responseOrderDTO.setDate(com.proj.my.util.DateUtil.getCurrentDateTime());
responseOrderDTO.setOrderId(order.getId());
return ResponseEntity.ok(responseOrderDTO);
}
else{
return new ResponseEntity<>("Can't create an order without products.", HttpStatus.OK);
}
}
else{
return new ResponseEntity<>("No Product with such name found.", HttpStatus.OK);
}
}
return null;
}}
Let me know if you need the rest of the services and, or controllers of the other 2 entities.
How can I do this ?
I am having a hard time trying to figure out how to add a one to many relationship in my database. The Book entity needs to hold many Counts. When I tried it, I got an error that says:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.counter, PID: 11949
java.lang.RuntimeException: cannot find implementation for com.example.counter.db.AppDatabase. AppDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:97)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1358)
at com.example.counter.db.AppDatabase.getInstance(AppDatabase.java:18)
Here is what my AppDatabase Looks like:
package com.example.counter.db;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
#Database(entities = {Count.class, Book.class}, version = 2, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase instance;
public static AppDatabase getInstance(Context context){
if(instance != null){
return instance;
}else{
instance = Room.databaseBuilder(context, AppDatabase.class, "AppDatabase_database")
.build();
return instance;
}
}
public abstract CountDAO countDAO();
public abstract BookDAO bookDAO();
}
Count Entity:
package com.example.counter.db;
import androidx.room.Embedded;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import static androidx.room.ForeignKey.CASCADE;
#Entity
public class Count {
#PrimaryKey(autoGenerate = true)
private long count_id;
private long book_id;
private String title;
private Date date;
private int total;
public Count( long book_id, String title, Date date, int total) {
this.book_id = book_id;
this.title = title;
this.date = date;
this.total = total;
}
public long getCount_id() {
return count_id;
}
public void setCount_id(long id) {
this.count_id = id;
}
public long getBook_id() {
return book_id;
}
public void setBook_id(long book_id) {
this.book_id = book_id;
}
public String getCountTitle() {
return title;
}
public void setCountTitle(String title) {
this.title = title;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
#Override
public String toString() {
return "Count{" +
"id=" + count_id +
", book_id=" + book_id +
", title='" + title + '\'' +
", date=" + date +
", total=" + total +
'}';
}
}
Book Entity:
package com.example.counter.db;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.util.Date;
#Entity
public class Book {
#PrimaryKey(autoGenerate = true)
private long book_id;
private String title;
private Date date;
public Book(String title, Date date) {
this.title = title;
this.date = date;
}
public long getBook_id() {
return book_id;
}
public void setBook_id(long id) {
this.book_id = id;
}
public String getBookTitle() {
return title;
}
public void setBookTitle(String title) {
this.title = title;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Override
public String toString() {
return "Book{" +
"id=" + book_id +
", title=" + title +
", date=" + date +
'}';
}
}
BookWithCounts Entity
package com.example.counter.db;
import androidx.room.Embedded;
import androidx.room.Relation;
import java.util.List;
public class BookWithCounts {
#Embedded
public Book book;
#Relation(
parentColumn = "book_id",
entityColumn = "book_id"
)
public List<Count> counts;
public BookWithCounts(Book book, List<Count> counts){
this.book = book;
this.counts = counts;
}
}
CountDAO
package com.example.counter.db;
import androidx.room.Embedded;
import androidx.room.Relation;
import java.util.List;
public class BookWithCounts {
#Embedded
public Book book;
#Relation(
parentColumn = "book_id",
entityColumn = "book_id"
)
public List<Count> counts;
public BookWithCounts(Book book, List<Count> counts){
this.book = book;
this.counts = counts;
}
}
BookDAO
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Transaction;
import androidx.room.Update;
import java.util.List;
#Dao
public interface BookDAO {
#Query("select * from Book")
LiveData<List<Book>> getAllBooks();
#Query("select * from Book where book_id=:id")
List<Book> getBookByID(long id);
#Query("select title from Book")
LiveData<List<String>> getAllBookTitles();
#Insert
long insertBook(Book book);
#Insert
long insertCount(Count count);
#Update
void updateBook(Book book);
#Delete
void deleteBook(Book book);
}
BooksWithCountsDAO
package com.example.counter.db;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Transaction;
import java.util.List;
#Dao
public interface BookWithCountsDAO {
#Transaction
#Insert
long insertBook(Book book);
#Insert
void insertCounts(List<Count> counts);
}
I also have View Models for both Books and Counts that I use to fill a recycler view. However, I get the error when I try and view the recycler view.
[Update] I figured out the issue. It was a combination of things. First I didn't have the annotation processor dependency. These are the dependencies you need.
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
I also had issues with using a type Date with no date converter. I didn't want to mess with the date converter. So I simply just changed the type to a string. After I was able to get it working.
I have an auditing entity which defined like this:
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.io.Serializable;
import java.time.Instant;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
/**
* Base abstract class for entities which will hold definitions for created, last modified, created by,
* last modified by attributes.
*/
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
#CreatedBy
#Column(name = "created_by", nullable = false, length = 50, updatable = false)
#JsonIgnore
private String createdBy;
#CreatedDate
#Column(name = "created_date", updatable = false)
#JsonIgnore
private Instant createdDate = Instant.now();
#LastModifiedBy
#Column(name = "last_modified_by", length = 50)
#JsonIgnore
private String lastModifiedBy;
#LastModifiedDate
#Column(name = "last_modified_date")
#JsonIgnore
private Instant lastModifiedDate = Instant.now();
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
And this is the implementation:
import com.app.derin.uaa.config.Constants;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
/**
* Implementation of {#link AuditorAware} based on Spring Security.
*/
#Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
#Override
public Optional<String> getCurrentAuditor() {
return Optional.of(SecurityUtils.getCurrentUserName().orElse(Constants.SYSTEM_ACCOUNT));
}
}
But I also need to store Hostname of request ip ( if it can be acquired from browser/dns if not it can be null) and request ip.
I found some examples and i changed my class to this:
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.ColumnDefault;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.io.Serializable;
import java.time.Instant;
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity<T> implements Serializable {
#CreatedDate
#JsonIgnore
#Column(name = "created_date", updatable = false)
private Instant createdDate = Instant.now();
#CreatedBy
#JsonIgnore
#Column(name = "created_by", updatable = false)
#Embedded
private T createdBy;
#LastModifiedDate
#Column(name = "modified_date")
#JsonIgnore
private Instant modifiedDate = Instant.now();;
#LastModifiedBy
#Column(name = "modified_by")
#JsonIgnore
#Embedded
private T modifiedBy;
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public T getCreatedBy() {
return createdBy;
}
public void setCreatedBy(T createdBy) {
this.createdBy = createdBy;
}
public Instant getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Instant modifiedDate) {
this.modifiedDate = modifiedDate;
}
public T getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(T modifiedBy) {
this.modifiedBy = modifiedBy;
}
}
And my implementation to this:
import com.app.derin.configuration.config.Constants;
import java.util.Optional;
import com.app.derin.configuration.ext.AuditorDetails;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
/**
* Implementation of {#link AuditorAware} based on Spring Security.
*/
#Component
public class SpringSecurityAuditorAware implements AuditorAware<AuditorDetails> {
#Override
public Optional<AuditorDetails> getCurrentAuditor() {
AuditorDetails currentAuditor = new AuditorDetails();
currentAuditor.setLoggedUser(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM_ACCOUNT));
currentAuditor.setHostIp("ip");
return Optional.of(currentAuditor);
}
}
But if I am right hibernate doesn't support generic types. I am getting this error:
[ERROR] Error setting up or running Liquibase:
[ERROR] org.hibernate.AnnotationException: Property com.app.derin.configuration.ext.extendedFields.AbstractAuditingEntity.createdBy has an unbound type and no explicit target entity. Resolve this Generic usage issue or set an explicit targe
t attribute (eg #OneToMany(target=) or use an explicit #Type
Is there any way to achieve this?
I found solution and here is how did:
After a lot of googling i found that my problem is with hibernate annotation. I am trying to send Datatype that hibernate doesn't know about. So I changed my class to custom type for hibernate.
More info you can check this link. It helped me.
My AuditorDetails class:
import java.io.Serializable;
import java.util.Objects;
public final class AuditorDetails implements Serializable {
private final String loggedUser;
private final String hostName;
private final String hostIp;
public AuditorDetails(String loggedUser, String hostName, String hostIp) {
this.loggedUser = loggedUser;
this.hostName = hostName;
this.hostIp = hostIp;
}
public String getLoggedUser() {
return loggedUser;
}
public String getHostName() {
return hostName;
}
public String getHostIp() {
return hostIp;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AuditorDetails that = (AuditorDetails) o;
return Objects.equals(loggedUser, that.loggedUser) &&
Objects.equals(hostName, that.hostName) &&
Objects.equals(hostIp, that.hostIp);
}
#Override
public int hashCode() {
return Objects.hash(loggedUser, hostName, hostIp);
}
}
AuditorDetailsType class:
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class AuditorDetailsType implements UserType {
#Override
public int[] sqlTypes() {
return new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
}
#Override
public Class returnedClass() {
return AuditorDetails.class;
}
#Override
public boolean equals(Object o, Object o1) throws HibernateException {
if(o == o1)
return true;
if (Objects.isNull(o) || Objects.isNull(o1))
return false;
return o.equals(o1);
}
#Override
public int hashCode(Object o) throws HibernateException {
return o.hashCode();
}
#Override
public Object nullSafeGet(ResultSet resultSet, String[] strings, SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException, SQLException {
String loggedUser = resultSet.getString(strings[0]);
if(resultSet.wasNull())
return null;
String hostName = resultSet.getString(strings[1]);
String hostIp = resultSet.getString(strings[2]);
AuditorDetails currentAuditor = new AuditorDetails(loggedUser, hostName, hostIp);
return currentAuditor;
}
#Override
public void nullSafeSet(PreparedStatement preparedStatement, Object o, int i, SharedSessionContractImplementor sharedSessionContractImplementor) throws HibernateException, SQLException {
if (Objects.isNull(o)){
preparedStatement.setNull(i,Types.VARCHAR);
}
else {
AuditorDetails currentAuditor = (AuditorDetails) o;
preparedStatement.setString(i,currentAuditor.getLoggedUser());
preparedStatement.setString(i+1,currentAuditor.getHostName());
preparedStatement.setString(i+2,currentAuditor.getHostIp());
}
}
#Override
public Object deepCopy(Object o) throws HibernateException {
if (Objects.isNull(o))
return null;
AuditorDetails currentAuditor = (AuditorDetails) o;
return new AuditorDetails(currentAuditor.getLoggedUser(), currentAuditor.getHostName(), currentAuditor.getHostIp());
}
#Override
public boolean isMutable() {
return false;
}
#Override
public Serializable disassemble(Object o) throws HibernateException {
return (Serializable) o;
}
#Override
public Object assemble(Serializable serializable, Object o) throws HibernateException {
return serializable;
}
#Override
public Object replace(Object o, Object o1, Object o2) throws HibernateException {
return o;
}
}
AbstractAuditingEntity:
import com.app.derin.uaa.ext.AuditorDetails;
import com.app.derin.uaa.ext.AuditorDetailsType;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.TypeDef;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.Instant;
#TypeDef(name = "AuditorDetails",
typeClass = AuditorDetailsType.class,
defaultForType = AuditorDetails.class)
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity{
#CreatedDate
#JsonIgnore
#Column(name = "created_date", updatable = false)
private Instant createdDate = Instant.now();
#CreatedBy
#Columns(columns = {#Column(name = "created_by", updatable = false),
#Column(name = "created_host_name", updatable = false),
#Column(name = "created_host_ip", updatable = false)})
private AuditorDetails createdBy;
#LastModifiedDate
#Column(name = "modified_date")
#JsonIgnore
private Instant modifiedDate = Instant.now();
#LastModifiedBy
#Columns(columns = {#Column(name = "modified_by"),
#Column(name = "modified_host_name"),
#Column(name = "modified_host_ip")})
private AuditorDetails modifiedBy;
#Column(name = "row_status")
#JsonIgnore
#ColumnDefault("1")
private Integer rowStatus = 1;
protected AbstractAuditingEntity() {
}
public AuditorDetails getModifiedBy() {
return modifiedBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public AuditorDetails getCreatedBy() {
return createdBy;
}
public void setCreatedBy(AuditorDetails createdBy) {
this.createdBy = createdBy;
}
public Instant getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Instant modifiedDate) {
this.modifiedDate = modifiedDate;
}
public Integer getRowStatus() {
return rowStatus;
}
public void setRowStatus(Integer rowStatus) {
this.rowStatus = rowStatus;
}
}
SpringSecurityAuditorAware:
import com.app.derin.uaa.config.Constants;
import java.util.Optional;
import com.app.derin.uaa.ext.AuditorDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* Implementation of {#link AuditorAware} based on Spring Security.
*/
#Component
public class SpringSecurityAuditorAware implements AuditorAware<AuditorDetails> {
private final Logger log = LoggerFactory.getLogger(SpringSecurityAuditorAware.class);
#Override
public Optional<AuditorDetails> getCurrentAuditor() {
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = sra.getRequest();
if(request != null) {
String hostIp = getClientIpAddress(request);
String hostName = "";
AuditorDetails currentAuditor = new AuditorDetails(SecurityUtils.getCurrentUserName().orElse(Constants.SYSTEM_ACCOUNT),
hostName, hostIp);
return Optional.of(currentAuditor);
}
return Optional.of(currentAuditor);
}
private static final String[] IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR" };
public String getClientIpAddress(HttpServletRequest request) {
for (String header : IP_HEADER_CANDIDATES) {
String ip = request.getHeader(header);
log.info("ip : {}", ip);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
}
I have two table Parent table is Credit in that table only one row of data is there and another one is child table Debit that contains multiple row of data. how to fetch data from two table which has to match id of parent class and child class and no duplicate is shown from parent class.
I have try with (from Credit,debit) but that can display with duplicate and not properly data is shown based on id.
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}
}
1.CreditDaoImpl.java
package com.rojmat.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.rojmat.dao.CreditDao;
import com.rojmat.entity.Credit;
#Repository
public class CreditDaoImpl implements CreditDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addCreditDebit(Credit credit) {
try {
sessionFactory.getCurrentSession().saveOrUpdate(credit);
} catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void deleteCreditDebit(int cid) {
/*Credit credit = (Credit)sessionFactory.getCurrentSession().createQuery("from Credit as c LEFT JOIN FETCH c.Debit where c.cid="+cid).uniqueResult();
List<Debit> debits = credit.getDebit();
sessionFactory.getCurrentSession().delete(credit);
debits.forEach((debit) -> {
sessionFactory.getCurrentSession().delete(debit);
});*/
}
#SuppressWarnings("unchecked")
#Override
public List<Credit> getAllCreditDebit() {
List<Credit> credit = sessionFactory.getCurrentSession().createQuery("from Credit,Debit").list();
return credit;
}
}
try this example: you put "distinct" before the property you do not want to be duplicated
//SQL query
select distinct credit.idCredit as idCredit from Credit credit Left Join Debit debit on credit.idCredit= debit.idCredit
//HQL query
#Entity(name = "Credit")
#Table(name = "Credit")
public class Credit{
//if you put #Id --> HQL Query "select credit from Credit credit"
#Column(name = "idCredit")
private Long idCredit;
#Column(name = "label")
private String label;
#OneToMany
#JoinColumns({#JoinColumn(name = "idCredit" ,referencedColumnName = "idCredit")})
List<Debit> debits;
...
}
public class Debit{
....
#Column(name = "idCredit")
private Long idCredit;
...
}
Query query = getSession().createQuery("select distinct credit.idCredit as idCredit, credit.label as label, credit.debits as debits from Credit credit ");
query.setResultTransformer(Transformers.aliasToBean(Credit.class));
return query.list();
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/*#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}*/
}
import java.io.Serializable;
import java.util.Date;
import java.util.List;
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.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import org.hibernate.annotations.GenericGenerator;
import com.lue.billingsystem.enums.Status;
import com.lue.billingsystem.enums.Types;
#Entity
#Table(name="product_tab")
public class Product implements Serializable{
private static final long serialVersionUID = 8919320309645697466L;
#Id
#Column(name="prod_id",updatable=false)
#GenericGenerator(name="product_tab_genetator",strategy="increment")
#GeneratedValue(generator="product_tab_genetator")
private Long id;
private String name;
#Enumerated(EnumType.STRING)
#Column(name = "type")
private Types type;
#Column(name = "status")
#Enumerated(EnumType.STRING)
private Status status;
#Column(name = "description", length = 200)
private String description;
#OneToMany(mappedBy="product")
private List<Charge> charges;
#Column(name = "create_date", columnDefinition = "DATETIME")
private Date createDate;
#Column(name = "update_date", columnDefinition = "DATETIME")
private Date updateDate;
//#Version
private Integer version;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Types getType() {
return type;
}
public void setType(Types type) {
this.type = type;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Charge> getCharges() {
return charges;
}
public void setCharges(List<Charge> charges) {
this.charges = charges;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
}
import org.springframework.http.HttpStatus;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.lue.billingsystem.enums.utils.StatusDeserializer;
import com.lue.billingsystem.exception.BillingException;
#JsonDeserialize(using = StatusDeserializer.class)
public enum Status {
ACTIVE("Active"), INACTIVE("Inactive");
private final String text;
Status(final String text) {
this.text = text;
}
#Override
public String toString() {
return text;
}
public String getText() {
return this.text;
}
public static Status fromText(String text) {
for (Status r : Status.values()) {
if (r.getText().equals(text)) {
System.out.println(r);
return r;
}
}
throw new BillingException("Your Status not valied: "+text +" ", HttpStatus.BAD_REQUEST, 400);
}
}
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
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.lue.billingsystem.enums.Status;
public class StatusDeserializer extends JsonDeserializer<Status> {
#Override
public Status deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
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;
}
//System.out.println(Status.fromText(text) + "---------------");
return Status.fromText(text);
}
}
How to enum mapping with jpa Spring boot why not save enum value in DB in DB saving enum key when i saving product in databse not save status like Active it always save ACTIVE
You just need to pay attention to the enum values when the table is being created.
What are the enum values in the table e.g. in status column, are the values defined as 'Active', 'Inactive' or 'ACTIVE', 'INACTIVE'. That's what will determine the value saved.
If the enum values are defined as 'ACTIVE', 'INACTIVE', if you insert 'active' as the value for status, it will change to 'ACTIVE' inside the database because it inserts based on the pre defined enum values.