My tableview is displaying blank rows [duplicate] - mysql

This question already has answers here:
Javafx tableview not showing data in all columns
(3 answers)
Closed 7 years ago.
I am new to JavaFX and I have been trying to implement this code for displaying data from MySQL database in a TableView. The problem is that when I run the code I get blank rows and I don't know why.
Here is my code for the class:
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
public class FXMLPatientsMasterController implements Initializable {
/*
mysql connection variables
*/
Connection conn=null;
PreparedStatement pat=null;
ResultSet rs=null;
private ObservableList<PatientDetails> patients;
#FXML
private TableView Table_Patients;
#FXML
private TableColumn patientID;
#FXML
private TableColumn Name;
#FXML
private TableColumn Surname;
#FXML
private TableColumn pnationalID;
#FXML
private TableColumn psex;
#FXML
private TableColumn pDOB;
// Some code here
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
conn = PMS263MySqlConnection.ConnectDB();
try {
patients = FXCollections.observableArrayList();
rs = conn.createStatement().executeQuery("select * from patients");
while (rs.next()) {
patients.add(new PatientDetails(rs.getInt("PatientId"),
rs.getString("fName"), rs.getString("Surname"), rs.getString("National_ID"), rs.getString("Sex"), rs.getString("DOB")));
}
patientID.setCellValueFactory(new PropertyValueFactory("PatientId"));
Name.setCellValueFactory(new PropertyValueFactory("fName"));
Surname.setCellValueFactory(new PropertyValueFactory("Surname"));
pnationalID.setCellValueFactory(new PropertyValueFactory("National_ID"));
psex.setCellValueFactory(new PropertyValueFactory("Sex"));
pDOB.setCellValueFactory(new PropertyValueFactory("DOB"));
Table_Patients.setItems(null);
Table_Patients.setItems(patients);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
public static class PatientDetails {
private final SimpleIntegerProperty Patientid;
private final StringProperty Pname;
private final StringProperty Psurname;
private final StringProperty Pnationalid;
private final StringProperty Psex;
private final StringProperty Pdob;
private PatientDetails(int patientid, String pname, String psurname, String pnationalid, String psex, String pdob) {
this.Patientid = new SimpleIntegerProperty(patientid);
this.Pname = new SimpleStringProperty(pname);
this.Psurname = new SimpleStringProperty(psurname);
this.Pnationalid = new SimpleStringProperty(pnationalid);
this.Psex= new SimpleStringProperty(psex);
this.Pdob = new SimpleStringProperty(pdob);
}
public SimpleIntegerProperty patientidProperty() {
return Patientid ;
}
public StringProperty pnameProperty() {
return Pname;
}
public StringProperty psurnameProperty() {
return Psurname;
}
public StringProperty pnationalidProperty() {
return Pnationalid;
}
public StringProperty psexPsexProperty() {
return Psex;
}
public StringProperty pdobProperty() {
return Pdob;
}
}
}

Assuming your database query works, you the property names wrong:
If the property "getter" is named myNameProperty() you need to use new PropertyValueFactory("myName").
Either the property "getters" need to be renamed or the strings used with the value factories:
patientID.setCellValueFactory(new PropertyValueFactory("patientId"));
Name.setCellValueFactory(new PropertyValueFactory("pname"));
Surname.setCellValueFactory(new PropertyValueFactory("psurname"));
pnationalID.setCellValueFactory(new PropertyValueFactory("pnationalid"));
psex.setCellValueFactory(new PropertyValueFactory("psex"));
pDOB.setCellValueFactory(new PropertyValueFactory("pdob"));
...
public SimpleIntegerProperty patientIdProperty() {
return Patientid;
}
public StringProperty pnameProperty() {
return Pname;
}
public StringProperty psurnameProperty() {
return Psurname;
}
public StringProperty pnationalidProperty() {
return Pnationalid;
}
public StringProperty psexProperty() {
return Psex;
}
public StringProperty pdobProperty() {
return Pdob;
}

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

Spring Boot: how can I parse a JSON which consists of an array of objects and use a path variable to get a specific value?

I've got the following task:
I need to Produce a Spring Boot REST API that reads in data from a JSON file and allows the user to filter by colour.
The URL should look similar to: http://localhost:8080/cars?colour=red
The input data is in the included JSON file (cars.json)
It is of the form:
{
"cars": [
{
"brand": "ford",
"model": "fiesta",
"fuel": "petrol",
"doors": 5,
"colour": "blue"
}
]
}
I'm struggling to structurize JSON parsing classes properly, and here's my code
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.challenge.esure.domain.Cars;
import com.challenge.esure.exceptions.ColourNotFoundException;
import com.challenge.esure.service.MainService;
#RestController
public class MainController {
private final MainService mainService;
#Autowired
public MainController(MainService mainService) {
this.mainService = mainService;
}
#GetMapping("/all")
public List<Cars> getAll() throws IOException {
return mainService.getAllRecords();
}
#GetMapping("/cars?colour={colour}")
public Cars getColour(#PathVariable("colour") String colour) throws IOException, ColourNotFoundException {
return mainService.getCarColour(colour);
}
}
//Service:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import com.challenge.esure.domain.CarDetails;
import com.challenge.esure.domain.Cars;
import com.challenge.esure.exceptions.ColourNotFoundException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
#Service
public class MainService {
public List<Cars> getData() throws IOException{
Resource resource = new ClassPathResource("cars.json");
InputStream input = resource.getInputStream();
File file = resource.getFile();
ObjectMapper objectMapper = new ObjectMapper();
List<Cars> car = Arrays.asList(objectMapper.readValue(file, Cars[].class));
return car.stream().collect(Collectors.toList());
}
public List<Cars> getAllRecords() throws IOException {
return getData();
}
public Cars getCarColour(String colour) throws ColourNotFoundException, IOException {
return getData().stream()
.filter(Cars -> Cars.getColour().equals(colour))
.findAny()
.orElseThrow(() -> new ColourNotFoundException("We don't have cars with that colour"));
}
}
// Domain
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Cars {
private ArrayList<Object> cars;
private String brand;
private String model;
private String fuel;
private Integer doors;
private String colour;
public Cars() {
}
public Cars(ArrayList<Object> cars, String brand, String model, String fuel, Integer doors, String colour) {
this.cars = cars;
this.brand = brand;
this.model = model;
this.fuel = fuel;
this.doors = doors;
this.colour = colour;
}
public ArrayList<Object> getCars() {
return cars;
}
public void setCars(ArrayList<Object> cars) {
this.cars = cars;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getFuel() {
return fuel;
}
public void setFuel(String fuel) {
this.fuel = fuel;
}
public Integer getDoors() {
return doors;
}
public void setDoors(Integer doors) {
this.doors = doors;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
//Exception
public class ColourNotFoundException extends Exception {
public ColourNotFoundException(String what) {
super(what);
}
}
You can use the below data structure
#JsonIgnoreProperties(ignoreUnknown = true)
public class CarResponse {
List<Car> cars;
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
#Override
public String toString() {
return "CarResponse{" +
"cars=" + cars +
'}';
}
}
public class Car {
private String brand;
private String model;
private String fuel;
private Integer doors;
private String colour;
}
CarResponse carResponse= objectMapper.readValue(jsonString, CarResponse.class);

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);
}
}

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;

How to parse recursive JSON object using JAXB

Below is my JSON, how to parse it using jaxb, note the depth and key of categories would change
{
"categories":{
"categoryHierarchy":[
{
"hierarchy":{
"SDG--1513417390":{
"SD-1501363638":{
"D-HS-MM4":{
"CL-HS-MM4-DEFAULT":{
"C-HS-MM4-MM0203":{
}
}
}
}
}
},
"precedence":1
}
]
}
}
After trying multiple things I was able to parse the recursive category structure.
package com.example;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pearson.aem.aemcore.pim.dto.com.example.Example;
class Parser{
private transient static ObjectMapper jsonMapper;
public static void main (String [] args) throws IOException
{
jsonMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String response = "{\"categoryHierarchy\":[{\"hierarchy\":{\"SDG--1513417390\":{\"SD-1501363638\":{\"D-HS-MM4\":{\"CL-HS-MM4-DEFAULT\":{\"C-HS-MM4-MM0203\":{}}}}}},\"precedence\":1}]}";
InputStream stream = new ByteArrayInputStream(response.getBytes());
Example ex = unmarshalJson(stream, Example.class);
System.out.println(ex.getCategoryHierarchy().get(0).getHierarchy1().getAdditionalProperties());
//System.out.println(ex.getCategoryHierarchy().get(0).getHierarchy().getAdditionalProperties().get("SDG--1513417390").keySet.iterator().next());
}
public static <T> T unmarshalJson(final InputStream result, final Class<T> declaredType) throws IOException
{
return (T) jsonMapper.readValue(result, declaredType);
}
}
----------------
package com.example;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.pearson.aem.aemcore.pim.dto.CategoryElementDTO;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Example
{
#XmlElement(
name = "categoryHierarchy")
private List<CategoryHierarchy> categoryHierarchy;
#XmlElement(
name = "relatedCategories")
private Map<String, CategoryElementDTO> relatedCategories;
public List<CategoryHierarchy> getCategoryHierarchy()
{
return categoryHierarchy;
}
public void setCategoryHierarchy(List<CategoryHierarchy> categoryHierarchy)
{
this.categoryHierarchy = categoryHierarchy;
}
public Map<String, CategoryElementDTO> getRelatedCategories()
{
return relatedCategories;
}
public void setRelatedCategories(Map<String, CategoryElementDTO> relatedCategories)
{
this.relatedCategories = relatedCategories;
}
}
------------
package com.example;
public class CategoryHierarchy
{
private Hierarchy hierarchy;
private Integer precedence;
public Hierarchy getHierarchy()
{
return hierarchy;
}
public void setHierarchy(Hierarchy hierarchy)
{
this.hierarchy = hierarchy;
}
public Integer getPrecedence()
{
return precedence;
}
public void setPrecedence(Integer precedence)
{
this.precedence = precedence;
}
}
---------------
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Hierarchy
{
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties()
{
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value)
{
this.additionalProperties.put(name, value);
}
}