Restrict null data result in mapping in JPA - json

Entity 1 PriceListDuration.java
package com.Pricing.Pricing_App.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonPropertyOrder({"priceListId","statusCode","startDate","endDate","orgId"})
#Entity
#Table(name = "qp_price_lists_all_b_AV")
public class PriceListDuration {
#Id
#Column(name = "PRICE_LIST_ID")
private String priceListId;
#Column(name = "status_code")
private String statusCode;
#Column(name = "start_date")
private String startDate;
#Column(name = "end_Date")
private String endDate;
#Column(name = "org_id")
private String orgId;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "PRICE_LIST_ID", referencedColumnName = "PRICE_LIST_ID")
private PriceListDetail pricelistdetails;
public PriceListDetail getPricelistdetails() {
return pricelistdetails;
}
public void setPricelistdetails(PriceListDetail pricelistdetails) {
this.pricelistdetails = pricelistdetails;
}
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "PRICE_LIST_ID", referencedColumnName = "PRICE_LIST_ID")
private List<PriceListItem> priceListItems;
public List<PriceListItem> getPriceListItems() {
return priceListItems;
}
public void setPriceListItems(List<PriceListItem> priceListItems) {
this.priceListItems = priceListItems;
}
public String getPriceListId() {
return priceListId;
}
public void setPriceListId(String priceListId) {
this.priceListId = priceListId;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
}
Entity 2: PriceListItem.java
package com.Pricing.Pricing_App.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonPropertyOrder({"pricingUOMCode","lineTypeCode","primaryPricingUOMFlag","priceListId","itemId","priceListItemId"})
#Entity
#Table(name = "QP_PRICE_LIST_ITEMS_AV")
public class PriceListItem implements Serializable {
private static final long serialVersionUID = 1L;
public PriceListItem() {
super();
}
#Column(name = "price_list_item_id")
private String priceListItemId;
#Column(name = "pricing_uom_code")
private String pricingUOMCode;
#Column(name = "line_type_code")
private String lineTypeCode;
#Column(name = "primary_pricing_uom_flag")
private String primaryPricingUOMFlag;
#Column(name = "price_list_id")
private String priceListId;
#Id
#Column(name = "item_id")
private String itemId;
// For 1-1 mapping
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "item_id", referencedColumnName = "inventory_item_id")
private ItemDetail itemDetails;
public ItemDetail getItemDetails() {
return itemDetails;
}
public void setItemDetails(ItemDetail itemDetails) {
this.itemDetails = itemDetails;
}
public String getPricingUOMCode() {
return pricingUOMCode;
}
public void setPricingUOMCode(String pricingUOMCode) {
this.pricingUOMCode = pricingUOMCode;
}
public String getLineTypeCode() {
return lineTypeCode;
}
public void setLineTypeCode(String lineTypeCode) {
this.lineTypeCode = lineTypeCode;
}
public String getPrimaryPricingUOMFlag() {
return primaryPricingUOMFlag;
}
public void setPrimaryPricingUOMFlag(String primaryPricingUOMFlag) {
this.primaryPricingUOMFlag = primaryPricingUOMFlag;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
}
Entity 3: ItemDetail.java
package com.Pricing.Pricing_App.model;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonPropertyOrder({"itemNumber","inventoryItemId","organizationId"})
#Entity
#Table(name = "egp_system_items_b_AV")
public class ItemDetail {
#Id
#Column(name = "inventory_item_id")
private String inventoryItemId;
#Column(name = "item_number")
private String itemNumber;
#Column(name = "organization_id")
private String organizationId;
public String getItemNumber() {
return itemNumber;
}
public void setItemNumber(String itemNumber) {
this.itemNumber = itemNumber;
}
public String getInventoryItemId() {
return inventoryItemId;
}
public void setInventoryItemId(String inventoryItemId) {
this.inventoryItemId = inventoryItemId;
}
public String getOrganizationId() {
return organizationId;
}
public void setOrganizationId(String organizationId) {
this.organizationId = organizationId;
}
}
We have three Entity where Entity1 is the owner and E1-E2 has 1-M mapping and E2-E3 has 1-1 Mapping.
My Controller:
package com.Pricing.Pricing_App.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.Pricing.Pricing_App.model.PriceListDuration;
import com.Pricing.Pricing_App.repository.PriceListDurationRepository;
#RestController
public class PriceListDurationController {
#Autowired
private PriceListDurationRepository priceListDurationRepository;
#GetMapping(value="/getBypriceListId")
public List<PriceListDuration> getBypriceListId(#RequestParam("priceListId") String priceListId) {
return priceListDurationRepository.findBypriceListId(priceListId);
}
}
Here is the JSON ouput
[
{
"priceListId": "300002009417575",
"statusCode": "APPROVED",
"startDate": "1998-12-31 00:00:00",
"endDate": null,
"orgId": "300001096431127",
"pricelistdetails": {
"priceListId": "300002009417575",
"name": "COMMERCIAL PRICELIST",
"description": "COMMERCIAL PRICELIST",
"language": "US"
},
"priceListItems": [
{
"pricingUOMCode": "zzx",
"lineTypeCode": "ORA_BUY",
"primaryPricingUOMFlag": "Y",
"itemId": "100000763258696",
"itemDetails": {
"itemNumber": "SAM-SOLO-P2-PT",
"inventoryItemId": "100000763258696",
"organizationId": "300000245868293"
}
},
{
"pricingUOMCode": "zzx",
"lineTypeCode": "ORA_BUY",
"primaryPricingUOMFlag": "Y",
"itemId": "100000763259581",
"itemDetails": null
}
]
}
]
As you can see ItemDetails (from Entity 3) is null.
I want to restrict those priceListItems block which has ItemDetails as null.
findBypriceListId returns me the JSON output as given above.
The output also has "itemDetails": null.
I do not want any block which is null in the result.
The expected JSON should not have
{
"pricingUOMCode": "zzx",
"lineTypeCode": "ORA_BUY",
"primaryPricingUOMFlag": "Y",
"itemId": "100000763259581",
"itemDetails": null
}
It seems the current implementation is doing outer join

As the best way is while restricting the data in case of retrieving is not much better approach .Rather than you need to restrict data while saving it to table that if it's not null then only you save the column.
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "item_id", referencedColumnName = "inventory_item_id")
#NotNull
private ItemDetail itemDetails;

Related

java.sql.SQLIntegrityConstraintViolationException: Post method is not working for one to many mapping in Spring Boot

I use the technologies jpa, hibernate, spring boot - data, api REST, MySql
Please help me out regarding this ERROR..!
Hibernate: select creditcard0_.credit_id as credit_i1_2_0_, creditcard0_.cardno as cardno2_2_0_, creditcard0_.creditname as creditna3_2_0_, creditcard0_.cvv as cvv4_2_0_, creditcard0_.uid as uid5_2_0_ from credit_card creditcard0_ where creditcard0_.credit_id=? Hibernate: insert into credit_card (cardno, creditname, cvv, uid, credit_id) values (?, ?, ?, ?, ?) 2022-12-22 11:39:10.208 WARN 2368 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000 2022-12-22 11:39:10.208 ERROR 2368 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'uid' cannot be null 2022-12-22 11:39:10.209 INFO 2368 --- [nio-8080-exec-4] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements 2022-12-22 11:39:10.223 ERROR 2368 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'uid' cannot be null at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-j-8.0.31.jar:8.0.31] at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-j-8.0.31.jar:8.0.31] at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916) ~[mysql-connector-j-8.0.31.jar:8.0.31] at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1061) ~[mysql-connector-j-8.0.31.jar:8.0.31]
Here is my code:
**User.java**
import java.io.Serializable; import java.util.Set;
import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.transaction.Transactional;
import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
#Transactional #Entity #Table(name="users") public class User {
#Id
#GeneratedValue(strategy= GenerationType.AUTO,generator="native")
#GenericGenerator(name = "native",strategy = "native")
private int id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
#Column(name="phoneno")
private int phone_no;
#Column(name="address")
private String address;
private String pwd;
#OneToMany(mappedBy = "user",fetch=FetchType.LAZY,cascade = CascadeType.ALL)
private Set<CreditCard> creditcard;
public User() {
}
public User(String name, String email, int phone_no, String address, String pwd) {
super();
this.name = name;
this.email = email;
this.phone_no = phone_no;
this.address = address;
this.pwd=pwd;
}
public Set<CreditCard> getCreditcard() {
return creditcard;
}
public void setCreditcard(Set<CreditCard> creditcard) {
this.creditcard = creditcard;
}
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 String getEmail() {
return email;
}
public void setEmail_id(String email) {
this.email = email;
}
public int getPhone_no() {
return phone_no;
}
public void setPhone_no(int phone_no) {
this.phone_no = phone_no;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
#Override
public String toString() {
return "User [uid=" + id + ", name=" + name + ", email=" + email + ", phone_no=" + phone_no
+ ", address=" + address + ", pwd=" + pwd + "]";
}
}
**CreditCard.java**
import java.io.Serializable;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.transaction.Transactional;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Transactional
#Entity
#Table(name="credit_card")
public class CreditCard implements Serializable {
#Id
private int credit_id;
private String cardno;
private String cvv;
private String creditname;
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne(fetch=FetchType.LAZY,optional = true)
#JoinColumn(name="uid",nullable = true)
private User user;
public CreditCard() {
super();
// TODO Auto-generated constructor stub
}
public CreditCard( String cardno, String cvv, String creditname,User user) {
super();
//this.credit_id = credit_id;
this.cardno = cardno;
this.cvv = cvv;
this.creditname = creditname;
this.user=user;
}
public int getCredit_id() {
return credit_id;
}
public void setCredit_id(int credit_id) {
this.credit_id = credit_id;
}
public String getCardno() {
return cardno;
}
public void setCardno(String cardno) {
this.cardno = cardno;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String getCreditname() {
return creditname;
}
public void setCreditname(String creditname) {
this.creditname = creditname;
}
#JsonIgnore
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public String toString() {
return "CreditCard [credit_id=" + credit_id + ", cardno=" + cardno + ", cvv=" + cvv + ", creditname="
+ creditname + "]";
}
}
**UserController.java**
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.Grocery.Grocery.model.User;
import com.Grocery.Grocery.repository.GroceryRepository;
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private GroceryRepository groceryRepository;
#GetMapping
public List<User> getAllUsers()
{
return groceryRepository.findAll();
}
#GetMapping("/{id}")
public ResponseEntity getbyid(#PathVariable("id") int id) {
return new ResponseEntity(groceryRepository.findById(id), HttpStatus.OK);
}
}
**CreditCardController.java**
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.Grocery.Grocery.model.CreditCard;
import com.Grocery.Grocery.repository.CreditCardRepository;
#RestController
#RequestMapping("/creditcard")
public class CreditCardController {
#Autowired
private CreditCardRepository creditcardRepository;
#GetMapping
public List<CreditCard> getAllCreditCard(){
return creditcardRepository.findAll();
}
#PostMapping("/add")
#ResponseBody
public CreditCard createEmployee(#RequestBody CreditCard credit) {
return creditcardRepository.save(credit);
}
}
**GroceryRepository.java(UserRepository.java)**
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
import com.Grocery.Grocery.model.User;
#Repository
public interface GroceryRepository extends JpaRepository<User, Integer> {
List<User> findByEmail(String email);
}
**CreditCardRepository.java**
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.Grocery.Grocery.model.CreditCard;
#Repository
public interface CreditCardRepository extends JpaRepository<CreditCard, Integer>{
}
aaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaf awe fffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeee eeeeeeeeeeeeeeeeeeeeee eeeggg gggg gggggggggggggggggg kkkkkkkkkkkkkkkkkkk

SpringBoot #OneToMany Postman Request not working

1.User Class with OneToMany Annotation in relation to Roles class that can be many
2.Roles Class with #ManyToOne and #JoinColumn Annotation
3.Controller class with the endpoint
4.Postman request with Json Object throws an Exception, JSON parse error: Cannot deserialize instance of com.cvt.programmingTask.model.User out of START_ARRAY token
Class User()
package com.cvt.programmingTask.model;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email_id", unique=true)
private String emailId;
#OneToMany(mappedBy = "user")
private Set<Roles> roles;
public User() {
}
public User(String firstName, String lastName, String emailId, Set<Roles> roles) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
this.roles = roles;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public Set<Roles> getRoles() {
return roles;
}
public void setRoles(Set<Roles> roles) {
this.roles = roles;
}
}
Class Roles :
package com.cvt.programmingTask.model;
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.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="roles")
public class Roles {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "name")
private String name;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="user_id", nullable=false)
private User user;
public Roles() {
}
public Roles(Long id, String name, User user) {
super();
this.id = id;
this.name = name;
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
User Controller Java File
package com.cvt.programmingTask.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import com.cvt.programmingTask.exception.ResourceNotFoundException;
import com.cvt.programmingTask.model.User;
import com.cvt.programmingTask.repository.UserRepository;
/**
* #author edibi
*
*/
//#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/api/v1")
public class UserController {
#Autowired
private UserRepository userRepository;
//get all users
#GetMapping("/users")
public List<User> getAllUsers(){
return userRepository.findAll();
}
//create user rest api
#PostMapping("/users")
public User createUser(#RequestBody User user) {
return userRepository.save(user);
}
//get user
#GetMapping ("/users/{id}")
public ResponseEntity<User> getUserById(#PathVariable Long id) {
User user = userRepository.findById(id)
.orElseThrow(()->new ResourceNotFoundException("User does not exist with id : " +id));
return ResponseEntity.ok(user);
}
//update user
#PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(#PathVariable Long id, #RequestBody User userDetails){
User user = userRepository.findById(id)
.orElseThrow(()->new ResourceNotFoundException("User does not exist with id : " +id));
user.setFirstName(userDetails.getFirstName());
user.setLastName(userDetails.getLastName());
user.setEmailId(userDetails.getEmailId());
user.setRoles(userDetails.getRoles());
User updatedUser = userRepository.save(user);
return ResponseEntity.ok(updatedUser);
}
//delete User rest api
#DeleteMapping("/users/{id}")
public ResponseEntity< Map<String, Boolean> >deleteUser(#PathVariable Long id){
User user = userRepository.findById(id)
.orElseThrow(()->new ResourceNotFoundException("User does not exist with id : " +id));
userRepository.delete(user);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return ResponseEntity.ok(response);
}
}
Can you help me out really don't know what'S wrong. Thanks

SpringBoot - MySQL

I have created a Spring Boot REST API with inbuilt Apache Derby database. It worked fine. Now I have to integrate it with MySQL. I have updated POM.XML and configured the driver.
Expense.java
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 = "vendor")
public class Expense {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
private String vendorId;
#Column
private String vendorName;
#Column
private int vendorPhone;
#Column
private int vendorBalance;
#Column
private int vendorChequeAmount;
public String getVendorId() {
return vendorId;
}
public void setVendorId(String vendorId) {
this.vendorId = vendorId;
}
public String getVendorName() {
return vendorName;
}
public void setVendorName(String vendorName) {
this.vendorName = vendorName;
}
public int getVendorPhone() {
return vendorPhone;
}
public void setVendorPhone(int vendorPhone) {
this.vendorPhone = vendorPhone;
}
public int getVendorBalance() {
return vendorBalance;
}
public void setVendorBalance(int vendorBalance) {
this.vendorBalance = vendorBalance;
}
public int getVendorChequeAmount() {
return vendorChequeAmount;
}
public void setVendorChequeAmount(int vendorChequeAmount) {
this.vendorChequeAmount = vendorChequeAmount;
}
public Expense(String vendorId, String vendorName, int vendorPhone, int vendorBalance, int vendorChequeAmount) {
super();
this.vendorId = vendorId;
this.vendorName = vendorName;
this.vendorPhone = vendorPhone;
this.vendorBalance = vendorBalance;
this.vendorChequeAmount = vendorChequeAmount;
}
application.properties
server.port = 8087
server.contextPath=/expense-tracker
spring.datasource.url=jdbc:mysql://localhost:3306/web_customer_tracker
spring.datasource.username=springstudent
spring.datasource.password=springstudent
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
Please click for the MySQL details
When I run using Postman, I am getting 404 error. Something is wrong with MySQL configuration. Please help to identify it. Thanks
[EDIT]
ExpenseController.Java
package com.shef.expensetracker.expense;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RestController;
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
#RestController
#RequestMapping("/vendors")
public class ExpenseController {
#Autowired
private ExpenseService expenseService;
#GetMapping
public List<Expense> getAllExpenses(){
return expenseService.findAll();
}
#GetMapping(path = {"/{vendorId}"})
public Expense getExpense(#PathVariable String vendorId){
return expenseService.getExpenseById(vendorId);
}
#PostMapping
public void addExpense(#RequestBody Expense expense){
expenseService.addExpense(expense);
}
#PutMapping(path = {"/{vendorId}"})
public void updateExpense(#RequestBody Expense expense, #PathVariable String vendorId){
expenseService.updateExpense(expense,vendorId );
}
#DeleteMapping(path = {"/{vendorId}"})
public void deleteExpense( #PathVariable String vendorId){
expenseService.deleteExpense(vendorId );
}
}
ExpenseService.Java
package com.shef.expensetracker.expense;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class ExpenseService {
#Autowired
private ExpenseRepository expenseRepository;
/*private List<Expense> expenses = new ArrayList<>(
Arrays.asList(new Expense("1","Chicken", 1234, 500, 100),
new Expense("2","Mutton", 1234, 600, 100),
new Expense("3","Beef", 1234, 700, 100)
));*/
public List<Expense> findAll(){
List<Expense> expenses = new ArrayList<>();
expenseRepository.findAll().forEach(expenses::add);
return expenses;
}
public void addExpense(Expense expense) {
//expenses.add(expense);
expenseRepository.save(expense);
}
public Expense getExpenseById(String vendorId){
return expenseRepository.findOne(vendorId);
}
public void updateExpense(Expense expense, String vendorId) {
// TODO Auto-generated method stub
expenseRepository.save(expense);
}
public void deleteExpense(String vendorId) {
expenseRepository.delete(vendorId);
}
}
ExpenseTrackerApplication.Java
package com.shef.expensetracker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ExpenseTrackerApplication {
public static void main(String[] args) {
SpringApplication.run(ExpenseTrackerApplication.class, args);
}
}

IllegalArgumentException: MetaClass not found

I use a framework called "Cuba.Studio" to create a CRUD application.
When I use this JPQL Query, I get this exception:
Error com.haulmont.cuba.core.global.RemoteException: MetaClass not
found for firstusecase$FIRSTUSECASE_USE_CASE_PROJECT_LINK
this is my code:
try (Transaction tx = persistence.createTransaction()) {
EntityManager em = persistence.getEntityManager();
Query query = em.createQuery("select firstusecase$Project.name from
firstusecase$UseCase useCase,
firstusecase$FIRSTUSECASE_USE_CASE_PROJECT_LINK commonTable,
firstusecase$Project project where useCase.id = commonTable.use_case_id
and project.id = commonTable.project_id and useCase.id = :useCaseId")
.setParameter("useCaseId", useCase.getId());
and here is a part of the code of my Entity Class:
#JoinTable(name = "FIRSTUSECASE_USE_CASE_PROJECT_LINK",
joinColumns = #JoinColumn(name = "USE_CASE_ID"),
inverseJoinColumns = #JoinColumn(name = "PROJECT_ID"))
#ManyToMany
protected Collection<Project> project;
Does anybody have an idea?
I would be very thankful about your support :)
Thanks
EDIT:
Here is the code of the UseCase Class
package com.company.firstusecase.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Collection;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import com.haulmont.cuba.core.entity.StandardEntity;
import javax.persistence.Column;
import com.haulmont.chile.core.annotations.NamePattern;
import javax.persistence.Lob;
import com.haulmont.chile.core.annotations.MetaProperty;
import javax.persistence.Transient;
#NamePattern("%s|jamaref")
#Table(name = "FIRSTUSECASE_USE_CASE")
#Entity(name = "firstusecase$UseCase")
public class UseCase extends StandardEntity {
private static final long serialVersionUID = 4928397068727365740L;
#Column(name = "JAMAREF", length = 30)
protected String jamaref;
#Column(name = "PROJECT_LIST")
protected String projectList;
#Transient
#MetaProperty
protected String usecaseDescription;
#Column(name = "CHANGE_TRACKING_COMMENT")
protected String changeTrackingComment;
#Lob
#Column(name = "CHANGE_TRACKING")
protected String changeTracking;
#Column(name = "POWERAMSREF", length = 30)
protected String poweramsref;
#Column(name = "LEGACYPWRUC", length = 30)
protected String legacypwruc;
#Column(name = "TRACKING_CHANGE_COMMENT")
protected String trackingChangeComment;
#Column(name = "INSERT_TIMESTAMP")
protected String insertTimestamp;
#Column(name = "USECASE_TYPE")
protected String usecaseType;
#Column(name = "CHANGE_TIMESTAMP")
protected String changeTimestamp;
#JoinTable(name = "FIRSTUSECASE_USE_CASE_PROJECT_LINK",
joinColumns = #JoinColumn(name = "USE_CASE_ID"),
inverseJoinColumns = #JoinColumn(name = "PROJECT_ID"))
#ManyToMany
protected Collection<Project> project;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "USECASE_STATUS_ID")
protected UseCaseStatus usecaseStatus;
public void setProjectList(String projectList) {
this.projectList = projectList;
}
public String getProjectList() {
return projectList;
}
public String getUsecaseDescription() {
return usecaseDescription;
}
public void setChangeTrackingComment(String changeTrackingComment) {
this.changeTrackingComment = changeTrackingComment;
}
public String getChangeTrackingComment() {
return changeTrackingComment;
}
public void setChangeTracking(String changeTracking) {
this.changeTracking = changeTracking;
}
public void setInsertTimestamp(String insertTimestamp) {
this.insertTimestamp = insertTimestamp;
}
public void setChangeTimestamp(String changeTimestamp) {
this.changeTimestamp = changeTimestamp;
}
public String getInsertTimestamp() {
return insertTimestamp;
}
public void setUsecaseType(String usecaseType) {
this.usecaseType = usecaseType;
}
public String getUsecaseType() {
return usecaseType;
}
public String getChangeTimestamp() {
return changeTimestamp;
}
public String getChangeTracking() {
return changeTracking;
}
public void setTrackingChangeComment(String trackingChangeComment) {
this.trackingChangeComment = trackingChangeComment;
}
public String getTrackingChangeComment() {
return trackingChangeComment;
}
public void setUsecaseStatus(UseCaseStatus usecaseStatus) {
this.usecaseStatus = usecaseStatus;
}
public UseCaseStatus getUsecaseStatus() {
return usecaseStatus;
}
public void setJamaref(String jamaref) {
this.jamaref = jamaref;
}
public String getJamaref() {
return jamaref;
}
public void setPoweramsref(String poweramsref) {
this.poweramsref = poweramsref;
}
public String getPoweramsref() {
return poweramsref;
}
public void setLegacypwruc(String legacypwruc) {
this.legacypwruc = legacypwruc;
}
public String getLegacypwruc() {
return legacypwruc;
}
public void setProject(Collection<Project> project) {
this.project = project;
}
public Collection<Project> getProject() {
return project;
}
}
And the code of the Project.class
package com.company.firstusecase.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import com.haulmont.cuba.core.entity.StandardEntity;
import com.haulmont.chile.core.annotations.NamePattern;
#NamePattern("%s|name")
#Table(name = "FIRSTUSECASE_PROJECT")
#Entity(name = "firstusecase$Project")
public class Project extends StandardEntity {
private static final long serialVersionUID = -3997556855391197754L;
#Column(name = "NAME", nullable = false)
protected String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Thanks

Hibernate one to many input using json with POSTMAN

The problem is one to many hibernate mapping is not working in this json format. I think it's a logical error, syntax error is not shown.
My Controller is:
#RequestMapping(value = "/save", method = RequestMethod.POST, produces =MediaType.APPLICATION_JSON_VALUE,headers="Accept=application/json,application/xml")
public #ResponseBody JsonRecord setCurrentDataList(#RequestBody Employee emp) {
try {
int id=employeeServices.save(emp);
} catch (Exception e) {
return new JsonRecord(false,e.getMessage());
}
return new JsonRecord(true,"Successful",emp);
}
Employee Entity Class is:
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.IndexColumn;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
#Table(name="Employee")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE)
public class Employee implements Serializable{
private static final long serialVersionUID = -723583058586873479L;
#Id
#GeneratedValue
#Column(name ="empId")
#JsonProperty("empId")
private Integer empId;
#JsonProperty("empName")
private String empName;
#JsonProperty("empAddress")
private String empAddress;
#JsonProperty("salary")
private double salary;
#JsonProperty("empAge")
private Integer empAge;
#OneToMany(mappedBy="employee",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#Fetch(FetchMode.SELECT)
private List<Education> education;
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public double getSalary() {
return salary;
}
public void setSalary(double d) {
this.salary = d;
}
public Integer getEmpAge() {
return empAge;
}
public void setEmpAge(Integer empAge) {
this.empAge = empAge;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "employee")
#JsonManagedReference
public List<Education> getEducation() {
return education;
}
public void setEducation(List<Education> education) {
this.education = education;
}
}
Education Entity is:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
#Table(name="Education")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE)
public class Education{
#Id
#GeneratedValue
#Column(name ="eduID")
#JsonProperty("eduID")
private int eduID;
#JsonProperty("qualification")
private String qualification;
#JsonProperty("stream")
private String stream;
#ManyToOne
#JoinColumn(name="empid")
private Employee employee;
public int getEduID() {
return eduID;
}
public void setEduID(int eduID) {
this.eduID = eduID;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "empId", nullable = false)
#JsonBackReference
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
JSON input:
{
"empName": "myname",
"empAddress": "my address",
"salary": 1000,
"empAge": 24,
"education":[{
"qualification":"mca",
"stream":"mca"
}]
}
One to many mapping is not working with this json format.How to implement this mapping in json format? Please give me your valuable suggestions.
use
#OneToMany(cascade={CascadeType.ALL})
#Fetch(FetchMode.JOIN)
#JoinColumn(name="empId", referencedColumnName="empId")
private Set<Education> education;
instead of,
#OneToMany(mappedBy="employee",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#Fetch(FetchMode.SELECT)
private List<Education> education;