Spring JDBC Unable to insert - mysql

I am new to SpringBoot and I am using SpringBoot with JDBC for making an API. The INSERT is not working properly, I had made ID Unique and AutoIncremeneted it. Before I was inserting the ID and it was causing no problems.I am using MySql as the database.
The JSON I am using in POST is:
{
"name":"Name",
"email":"namegmail.com",
"dob":"2000-04-09",
"age":21
}
I am getting this Error.
{
"timestamp": "2021-06-20T13:10:16.925+00:00",
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'application/octet-stream' not supported",
"path": "/api/v1/NewStudent"
}
Controller
#RestController
#RequestMapping(path = "api/v1/")
public class StudentController {
private StudentService studentService;
#Autowired
public StudentController(StudentService service){
this.studentService=service;
}
#GetMapping("/home")
public String getHome(){
return "Hey Welcome to Home";
}
#PostMapping("/NewStudent")
public void registerNewStudent(#RequestBody StudentClass studentClass){
studentService.addNewStudent(studentClass);
}
#GetMapping("/student/{id}")
public StudentClass getStudentSearch(#PathVariable(value = "id") Long userId){
return studentService.getStudentSelect(userId);
}
#GetMapping("/AllStudents")
public List<StudentClass> getAllStudents(){
return studentService.getAllStudents();
}
}
StudentDao
public class StudentDaoClass implements StudentDao{
#Autowired
private JdbcTemplate jdbctemplate;
private List<StudentClass> selectAll;
#Override
public int insert(StudentClass student) {
String query="INSERT INTO Student(std_name,std_email,std_dob,std_age)" +
"VALUES(?,?,?,?)";
int res=this.jdbctemplate.update(query,student.getName(),student.getEmail(),student.getDob(),student.getId());
return res;
}
#Override
public StudentClass selectStudent(Long id) {
String query="SELECT * FROM Student WHERE std_id=?";
RowMapper<StudentClass> rowMapper=new RowMapperClass();
StudentClass studentClass=this.jdbctemplate.queryForObject(query,rowMapper,id);
return studentClass;
}
#Override
public List<StudentClass> selectAllStudents() {
String query="SELECT * FROM Student";
selectAll=this.jdbctemplate.query(query,new RowMapperClass());
return selectAll;
}
public JdbcTemplate getJdbctemplate() {
return jdbctemplate;
}
public void setJdbctemplate(JdbcTemplate jdbctemplate) {
this.jdbctemplate = jdbctemplate;
}
}
StudentClass
public class StudentClass {
#Id
private Long id;
private String name;
private LocalDate dob;
private Integer age;
private String email;
public StudentClass() {
}
public StudentClass(String name, String email,LocalDate dob ,Integer age) {
this.name = name;
this.dob = dob;
this.age = age;
this.email = email;
}
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 LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "StudentClass{" +
"id=" + id +
", name='" + name + '\'' +
", dob=" + dob +
", age=" + age +
", email='" + email + '\'' +
'}';
}
}

I think your rest call is not even reaching the jdbc part as there is problem in your rest request. I believe you are not setting the content-type properly. Try making below changes and see.
When sending the request please set 'Content-Type' header property to 'application/json'
and enhance your below handler method what is consumes.
#PostMapping(path="/NewStudent", consumes="application/json")
public void registerNewStudent(#RequestBody StudentClass studentClass){
studentService.addNewStudent(studentClass);
}
Try debugging your application. Your rest call should reach your above handler method.

Related

How to send values to parent table column in json

Customer entity
#Entity
#Table(name="Customer")
public class Customer {
#Id
#GeneratedValue
private Long cusId;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
#Column(name="address")
private String add;
#Column(name="tel")
private int tel;
#Column(name="email")
private String email;
#Column(name="userName")
private String username;
#Column(name="password")
private String password;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "customer")
#JsonManagedReference
private List<Complain> complain=new ArrayList<Complain>();
public Customer() {
super();
// TODO Auto-generated constructor stub
}
public Long getCusId() {
return cusId;
}
public void setCusId(Long cusId) {
this.cusId = cusId;
}
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 getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Complain> getComplain() {
return complain;
}
public void setComplain(List<Complain> complain) {
this.complain = complain;
}
}
Complain Entity
#Entity
#Table(name="Complain")
public class Complain {
#Id
#GeneratedValue
private Long id;
#Column(name="repfirst")
private String repfirst;
#Column(name="replast")
private String replast;
#Column(name="warranty")
private String warranty;
#Column(name="dop")
private String purDate;
#Column(name="Nomachine")
private String Nomachine;
#Column(name="Complain")
private String Complain;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="cus_id", referencedColumnName = "cusId")
#JsonBackReference
private Customer customer;
public Complain() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRepfirst() {
return repfirst;
}
public void setRepfirst(String repfirst) {
this.repfirst = repfirst;
}
public String getReplast() {
return replast;
}
public void setReplast(String replast) {
this.replast = replast;
}
public String getWarranty() {
return warranty;
}
public void setWarranty(String warranty) {
this.warranty = warranty;
}
public String getPurDate() {
return purDate;
}
public void setPurDate(String purDate) {
this.purDate = purDate;
}
public String getNomachine() {
return Nomachine;
}
public void setNomachine(String nomachine) {
Nomachine = nomachine;
}
public String getComplain() {
return Complain;
}
public void setComplain(String complain) {
Complain = complain;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
I want to pass data to the mysql database through the postman tool. How can I pass value for the foreign key column through the json query?
This is the method I have used in controller
#PostMapping(path="/",consumes="application/json",produces="application/json")
public void addComplain(#RequestBody Complain complain)
{
Integer id = complainService.getAllComplain().size()+1;
complain.setId(new Long(id));
complainService.createOrUpdateComplain(complain); }
After I send the request from the postman, all the data are saved except the foreign key. I think I missed something in mapping two tables.
This is my json query
{"complain":"No power",
"repfirst":"hi",
"replast":"all",
"warranty":"yes",
"purDate":"2020-02-29",
"nomachine":"6",
"tel":"46544654",
"Customer":[
{"cusId":"1"}
]
}
Database table image
Please help, Thanks in advance
{
"repfirst": "",
"replast": "",
"warranty": "",
"purDate" : "",
"Nomachine": "",
"Complain": "",
"cus_id": 1
}
That should work
"Customer":[
{"cusId":"1"}
]
This would work if you had Set<Customer> customers converted to an array in json, for example.

JSON Names from SpringFramework #Controller, #ResponseBody

I've got a simple Spring Controller who's purpose is to return a RESTful JSON response of my entity objects. Its returning the data in standard camelCase names which match my entity. However, I'd like the JSON names to match the database fields, which is simply TitleCase. Is there a simple way to do this? Below is a sample of the Controller and the JSON returned.
#Controller
#RequestMapping(path="/Users")
public class UserController {
#Autowired
private UserRepository userRepository;
#GetMapping(path="/List")
public #ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
}
Resulting JSON:
{"id":1,"userName":"SYSTEM","password":"xxxxx","firstName":"System","lastName":"System","phone":"XXX-XXX-XXXX","email":"system#test.com","reviewer":false,"admin":false}
Here's my User entity class:
package com.prs.business;
import java.io.Serializable;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name="username")
#JsonProperty("UserName")
private String userName;
private String password;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
private String phone;
private String email;
#Column(name="isreviewer")
private boolean reviewer;
#Column(name="isadmin")
private boolean admin;
#Column(name="isactive")
private boolean active;
#Column(name="datecreated")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
private Timestamp dateCreated;
public User() {
userName = "";
password = "";
}
public User(int id, String userName, String password, String firstName, String lastName, String phoneNumber,
String email, boolean reviewer, boolean admin) {
super();
this.id = id;
this.userName = userName;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.phone = phoneNumber;
this.email = email;
this.reviewer = reviewer;
this.admin = admin;
}
public User(String un, String pw, String fn, String ln, String pn, String e, boolean m, boolean a) {
setUserName(un);
setPassword(pw);
setFirstName(fn);
setLastName(ln);
setPhoneNumber(pn);
setEmail(e);
setReviewer(m);
setAdmin(a);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getPhone() {
return phone;
}
public void setPhoneNumber(String phoneNumber) {
this.phone = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isReviewer() {
return reviewer;
}
public void setReviewer(boolean inReviewer) {
this.reviewer = inReviewer;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean inAdmin) {
this.admin = inAdmin;
}
public boolean isActive() {
return admin;
}
public void setActive(boolean inActive) {
this.admin = inActive;
}
public Timestamp getDateCreated() {
return dateCreated;
}
public void setDateCreated(Timestamp dateCreated) {
this.dateCreated = dateCreated;
}
#Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", firstName=" + firstName
+ ", lastName=" + lastName + ", phoneNumber=" + phone + ", email=" + email + ", reviewer="
+ reviewer + ", admin=" + admin + "]";
}
}
How to enable pascal case for all JSON property names?
Put the following setting in your application.properties
spring.jackson.property-naming-strategy=UPPER_CAMEL_CASE
userRepository.findAll() will probably return a POJO, right?
In that pojo, before the getters or before the fields declaratin, you can add an annotion like
#JsonProperty("<hereYouWriteTheNameYouPrefer>")
private String userName;
or
private String userName;
#JsonProperty("<hereYouWriteTheNameYouPrefer>")
public String getUserName(){
return userName;
}

Spring Boot: Saving a one to many json request, foreign key is not saved automatically

I have 2 entities, Role and Resource. A role can have many resources.
#Entity
public class Resource {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
private String email;
#ManyToOne
#JoinColumn(name="roleId", nullable = false)
private Role role;
public int getId() {
return id;
}
public void setId(int 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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
#Entity
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "rolename")
private String roleName;
#OneToMany(mappedBy = "role", cascade = CascadeType.ALL)
private List<Resource> resources;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<Resource> getResources() {
return resources;
}
public void setResources(List<Resource> resources) {
this.resources = resources;
}
}
I'm trying to save a Role object that has a resource in it. This is the body of my json in postman.
{
"roleName" : "Business Analyst",
"resources" : [{
"firstName" : "John",
"lastName" : "Doe",
"email" : "John#Doe.com"
}]
}
http post call in postman:
http://localhost:8080/app/admin/roles/role
Role Controller
#RestController
#RequestMapping(value="/admin/roles")
public class RoleController {
#Autowired
private RoleService roleService;
private static final Logger log = LoggerFactory.getLogger(RoleController.class);
#RequestMapping(value="/role", method = RequestMethod.POST)
public ResponseEntity<?> addRole(#RequestBody Role role, UriComponentsBuilder ucBuilder){
log.info("Adding Role {}" + role);
log.info("Adding Rolename:" + role.getRoleName());
roleService.addRole(role);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/admin/roles/role/{id}").buildAndExpand(role.getId()).toUri());
return new ResponseEntity<String> (headers,HttpStatus.CREATED);
}
#RequestMapping(value="role", method = RequestMethod.GET)
public ResponseEntity<List<Role>> listAllRoles(){
List<Role> roles = roleService.getAllRoles();
return new ResponseEntity<List<Role>>(roles, HttpStatus.OK);
}
}
RoleRepository
public interface RoleRepository extends CrudRepository<Role, Integer> {
}
RoleService
public interface RoleService {
public void addRole(Role role);
}
RoleServiceImpl
#Service
public class RoleServiceImpl implements RoleService {
#Autowired
private RoleRepository roleRepository;
#Override
public void addRole(Role role) {
roleRepository.save(role);
}
}
Whats happening is, the role Business Analyst gets save in the roleName field of Role table. The id of the said row is auto generated. At the same time, the resource with firstName = John, lastName = Doe and email = John#Doe.com gets save in the Resource table.
However, the role_id is not being saved automatically in the Resource table so now it is null ( the table Resource has the role_id set to nullable ). I was expecting that when I do the json post, the data will be automatically saved in the Role table and also the Resource table. Both of these are happening except that the role_id is not being saved. What did I miss?
Change addRole like below :
public void addRole(Role role) {
for(Resource resource: role.getResources()){
resource.setRole(role);
}
roleRepository.save(role);
}

Entity creates useless id field

I have a CrudRepository with two entities.
Problem: The characteristic entity always creates an additional id field in the database but does not select the correct characteristic_id field to generate JSON.
machine entity
machine_id || name || description
characteristic entity
characteristic_id || machine_id || name || description || type || value
Question: Why does the characteristic entity always create an id field named id and does not use the definded filed characteristic_id?
JSON
How the entity manipulates the database layout:
Machine entity
#Entity
#Table(name = "maschine")
public class Machine {
private int machine_id;
private String name;
private String description;
private Set<Characteristic> characteristics;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "machine", cascade = CascadeType.ALL)
public Set<Characteristic> getCharacteristics() {
return characteristics;
}
public void setCharacteristics(Set<Characteristic> characteristics){
this.characteristics = characteristics;
}
public Machine(){}
public Machine(String name, String description){
this.name = name;
this.description = description;
}
#Override
public String toString() {
return "Machine [id=" + machine_id + ", name=" + name + ", description=" + description + "]";
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
public int getId() {
return machine_id;
}
public void setId(int machine_id) {
this.machine_id = machine_id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Characteristic entity
#Entity
#Table(name = "characteristic")
public class Characteristic {
private int characteristic_id;
private String name;
private String description;
private int type;
private int value;
private Machine machine;
#ManyToOne
#JoinColumn(name="machine_id")
public Machine getMachine(){
return machine;
}
public void setMachine(Machine machine){
this.machine = machine;
}
public Characteristic() {}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
public int getCharacteristic_Id() {
return characteristic_id;
}
public void setCharacteristic_Id(int characteristic_id) {
this.characteristic_id = characteristic_id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name="type")
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
#Column(name="value")
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
#Override
public String toString() {
return "Characteristic [id=" + characteristic_id + ", name=" + name + ", description=" + description + ", type=" + type
+ ", value=" + value + "]";
}
}
My CrudRepository to interact with the database:
public interface MachineRepository extends CrudRepository<Machine, Integer>{
}
My Controller:
#RestController
public class HomeController {
private final MachineRepository machineRepository;
#Autowired
HomeController(MachineRepository machineRepository) {
this.machineRepository = machineRepository;
}
#RequestMapping(value = "/machine", method = RequestMethod.GET)
Collection<Machine> readMachines(){
return (Collection<Machine>) machineRepository.findAll();
}
}
This is all code I have written for the database operations..
Change to this code
#Id
#GeneratedValue
#Column(name="id", nullable = false)
public int getCharacteristic_id() {
return characteristic_id;
}
By default as you have not specified the column name in your configuration hibernate will use the name of the getter methode without "get" part as the column name in the table. Below is the configuration in your Characteristic Entity
#Id
#GeneratedValue
public int getId() {
return characteristic_id;
}
As you have not specified any explicit column name for the memeber characteristic_id , hibernate by default chooses Id (removing get from the getId() method) as the column name for the member. And hence it always creates a column named Id for you characteristics_id member .
In order to force hibernate to use characteristic_id as the column name , you can use #Column annotation and provide the column name as characteristics_id
apart from the #Id and #GeneratedValue you are using to mark the getter.
#Id
#GeneratedValue
#Column(name="characteristic_id")
public int getId() {
return characteristic_id;
}
or you can change the name of getter and setter as below
#Id
#GeneratedValue
public int getCharacterisitc_id() {
return characteristic_id;
}
public void setCharacterisitc_id(int characteristic_id) {
this.characteristic_id = characteristic_id;
}

ResponseBody get object list from object. #JsonIgnore not working

Ok i have class User
#Entity
#Table(name = "users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long id_user;
#Column(nullable = false)
private String email;
#Column(nullable = true)
private String password;
private String firstname;
private String lastname;
private Boolean enabled;
private String phone;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_company")
private Company company;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_rank")
#JsonBackReference
private Authority authorities;
#OneToMany(mappedBy = "create_by")
private List<Cms> create_by;
#OneToMany(mappedBy = "modified_by")
private List<Cms> modified_by;
#OneToMany(mappedBy = "id_issuer")
private List<Ticket> id_issuer;
#OneToMany(mappedBy = "id_responsible")
private List<Ticket> id_responsible;
#OneToMany(mappedBy = "id_author")
private List<IssueMsg> id_author;
public User() {
}
public User(String email, String password, String firstname, String lastname, String phone, Company company, Authority authority) {
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
this.enabled = true;
this.phone = phone;
this.authorities = authority;
}
#Override
public String toString() {
return "User [id_user=" + id_user + ", email=" + email + ", password="
+ password + ", firstname=" + firstname + ", lastname="
+ lastname + ", enabled=" + enabled + ", phone=" + phone
+ "]";
}
public Long getId_user() {
return id_user;
}
public void setId_user(Long id_user) {
this.id_user = id_user;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#JsonIgnore
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
/**
* #return the authorities
*/
public Authority getAuthorities() {
return authorities;
}
/**
* #param authorities the authorities to set
*/
public void setAuthorities(Authority authority) {
this.authorities = authority;
}
#JsonIgnore
public List<Cms> getCreate_by() {
return create_by;
}
public void setCreate_by(List<Cms> create_by) {
this.create_by = create_by;
}
#JsonIgnore
public List<Cms> getModified_by() {
return modified_by;
}
public void setModified_by(List<Cms> modified_by) {
this.modified_by = modified_by;
}
#JsonIgnore
public List<Ticket> getId_issuer() {
return id_issuer;
}
public void setId_issuer(List<Ticket> id_issuer) {
this.id_issuer = id_issuer;
}
#JsonIgnore
public List<Ticket> getId_responsible() {
return id_responsible;
}
public void setId_responsible(List<Ticket> id_responsible) {
this.id_responsible = id_responsible;
}
#JsonIgnore
public List<IssueMsg> getId_author() {
return id_author;
}
public void setId_author(List<IssueMsg> id_author) {
this.id_author = id_author;
}
}
And class Company
#Entity
#Table(name = "companies")
public class Company implements Serializable {
private static final long serialVersionUID = 6255059577246367312L;
#Id
#GeneratedValue
private Long id_company;
private String name;
private String adress;
private String email;
private String phone;
#OneToMany(mappedBy = "company")
#JsonManagedReference
private List<User> user;
#Override
public String toString() {
return "Company [id_company=" + id_company + ", name=" + name
+ ", adress=" + adress + ", email=" + email + ", phone="
+ phone + "]";
}
public Company() {
}
public Company(Long id_company, String name, String adress, String email,
String phone) {
this.id_company = id_company;
this.name = name;
this.adress = adress;
this.email = email;
this.phone = phone;
}
public Long getId_company() {
return id_company;
}
public void setId_company(Long id_company) {
this.id_company = id_company;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
}
I getting all result from database, and returning this as response body.
My JSON response get user.company.user list and i don't need what. I was try add on getter company user #JsonIgnore but i getting error
com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: java.util.ArrayList[1]->projektzespolowy.model.User["company"]->projektzespolowy.model.Company_$$_jvstcb8_2["handler"])
I read many post about fix thix but no one help. This is possible to ignore this user list in company?
I think you are getting this exception because User#company is lazy fetched so jackson tries to serialize a hibernate proxy. Try with fetch = FetchType.EAGER on the mapping, or call user.getCompany() in the controller prior to returning the results.