I am trying to return json from these two entity classes.
Questions.java
#Entity
public class Questions {
#Id
#Column(name = "id")
private int id;
#Column(name = "question")
private String question;
#Column(name = "type")
private String type;
#Column(name = "description")
private String description;
#Column(name = "param")
private String param;
#Column(name = "maxlength")
private int maxlength;
#Column(name = "dependency")
private String dependency;
#OneToMany(mappedBy = "questions",targetEntity = Answers.class, cascade = CascadeType.ALL)
private Set<Answers> answers = new HashSet<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public int getMaxlength() {
return maxlength;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
public String getDependency() {
return dependency;
}
public Set<Answers> getAnswers() {
return answers;
}
public void setAnswers(Set<Answers> answers) {
this.answers = new HashSet<>(answers);
for(Answers answers1:answers){
answers1.setQuestions(this);
}
}
public void setDependency(String dependency) {
this.dependency = dependency;
}
}
Answers.java
#Entity
public class Answers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "ans_label")
private String ans_label;
#Column(name = "ans_value")
private int ans_value;
#Column(name = "ans_weightage")
private int ans_weightage;
#Column(name = "is_default")
private int is_default;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "ques_id", nullable = false)
private Questions questions;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAns_label() {
return ans_label;
}
public void setAns_label(String ans_label) {
this.ans_label = ans_label;
}
public int getAns_value() {
return ans_value;
}
public void setAns_value(int ans_value) {
this.ans_value = ans_value;
}
public int getAns_weightage() {
return ans_weightage;
}
public void setAns_weightage(int ans_weightage) {
this.ans_weightage = ans_weightage;
}
public int getIs_default() {
return is_default;
}
public void setIs_default(int is_default) {
this.is_default = is_default;
}
public Questions getQuestions() {
return questions;
}
public void setQuestions(Questions questions) {
this.questions = questions;
}
}
my controller looks like this.
SaveApiController
#RequestMapping("/getData")
public #ResponseBody List<Questions> getData(){
List<Questions> questionss=saveApiServices.getQuestions();
return questionss;
}
The json result i am currently getting has bunch of repeated values.
[{"id":1,"question":"१. व्यक्तिको पुरा नाम थर?", "type":"input_edittext",
"description":"","param":"smalltext","maxlength":20,"dependency":"",
"answers":
[{"id":0,"ans_label":"मुली","ans_value":1,"ans_weightage":0,"is_default":0,
"questions":{"id":1,"question":"१. व्यक्तिको पुरा नाम थर?",
"type":"input_edittext","description":"","param":"smalltext","maxlength":20
,"dependency":"","answers":[{"id":0,"ans_label":"मुली","ans_value":1,
"ans_weightage":0,"is_default":0,"questions":{"id":1,
"question":"१. व्यक्तिको पुरा नाम थर ?","type":"input_edittext",
"description":"","param":"smalltext","maxlength":20,"dependency":"",
"answers":[{"id":0,"ans_label":"मुली",
"ans_value":1,"ans_weightage":0,"is_default":0,"questions":{"id":1,
"question":"१. व्यक्तिको पुरा नाम थर ?","type":"input_edittext",
"description":"","param":"smalltext","maxlength":20,"dependency":"",
my database has only one row inserted. and on my controller there is only one list of questions found. but whenever json output is thrown it repeats a lot of same rows like in the above json sample.
what might be the problems? if you can't find the complete solution can you please suggest me the reason behind the duplication of the same values in json format?
Jackson is getting in a loop here. Your Questions class has a link to Answers and that class refers back to Questions.
Solution
Mark the questions field or the getter in the Answers class as #JsonIgnored.
You can try #JsonManagedReference and #JsonBackReference annotations
For Jackson to work well, one of the two sides of the relationship should not be serialized, in order to avoid the infite loop that causes your stackoverflow error.
#OneToMany(mappedBy = "questions",targetEntity = Answers.class, cascade = CascadeType.ALL)
#JsonManagedReference
private Set<Answers> answers = new HashSet<>();
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "ques_id", nullable = false)
#JsonBackReference
private Questions questions;
Or
If not interested in getting some entity data just use #JsonIgnore in any one of the class
Related
good day everyone,
i have this project where i use the ModelMapper to mat my entities to DTOs and vise-versa, and also have a class with #ElementCollection relation.
the mapper seems to work fine for all other methods and it just output the entity as i want, however when it comes to delete mapping i get the following error printed along with a 500 http status. here's the error:
"ModelMapper mapping errors:\r\n\r\n1) Converter org.modelmapper.internal.converter.CollectionConverter#ddb7bc7 failed to convert java.util.List to java.util.List.\r\n\r\n1 error"
here is code:
the entity class:
#Entity
#Table(name = "quiz_engines")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(
value = {"lastModified"},
allowGetters = true
)
public class Engine implements Model {
#Id
#Column(name = "engine_id", unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.LAZY,optional = false, targetEntity = com.QCMGenerator.QCMGenerator.Model.Test.class)
#JoinColumn(name = "test_id", referencedColumnName = "test_id", nullable = false, updatable = false)
#OnDelete(action = OnDeleteAction.NO_ACTION)
#JsonIgnore
private Test test;
#Column(name = "quiz_name", nullable = false)
#NotNull
private String name;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "last_modified", nullable = false)
#LastModifiedDate
private Date lastModified;
#ElementCollection
#CollectionTable(name = "engine_constraints", joinColumns = #JoinColumn(name = "engine_id"))
private List<EngineConstraint> constraints;
public Engine() {
}
public Engine(#NotNull String name, List<EngineConstraint> constraints) {
this.name = name;
this.constraints = constraints;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public List<EngineConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<EngineConstraint> constraints) {
this.constraints = constraints;
}
}
the DTO class:
public class EngineDTO implements ModelDTO {
private Long id;
#JsonIgnore
private TestDTO test;
private String name;
private Date lastModified;
private List<EngineConstraint> constraints;
public EngineDTO() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public TestDTO getTest() {
return test;
}
public void setTest(TestDTO test) {
this.test = test;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public List<EngineConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<EngineConstraint> constraints) {
this.constraints = constraints;
}
}
the Delete Controller:
#DeleteMapping("/{engineID}")
public ResponseEntity<NonPaginatedResponse> deleteEngine(
#PathVariable(value = "testID") Long testID,
#PathVariable(value = "engineID") Long engineID
){
if(!testRepo.existsById(testID)){
throw new ResourceNotFoundException("No test with the ID '"+testID+"' was found...");
}
return engineRepo.findById(engineID).map(engineFound -> {
engineRepo.delete(engineFound);
return ResponseEntity.status(HttpStatus.OK).body(
ResponseBodyBuilder.getSingleResponse(
convertToDTO(engineFound),
new ModelDTO[]{ convertToDTO(testRepo.findById(testID).get()) },
"delete"
)
);
}
).orElseThrow(
() -> new ResourceNotFoundException("No Engine with the ID '"+engineID+"' was found...")
);
}
hope you guys can help with this one, thank for your time everyone and have a good day.
I have been scratching my head for more than an hour and being unable to find solutions. i have two entities classes. one of them being Questions.java and other being Answers.java
Question.java
#Entity
#Table
public class Questions {
#Id
#Column(name = "ques_id")
private int ques_id;
#Column(name = "question")
private String question;
#Column(name = "type")
private String type;
#Column(name = "description")
private String description;
#Column(name = "param")
private String param;
#Column(name = "maxlength")
private int maxlength;
#Column(name = "dependency")
private String dependency;
#OneToMany(mappedBy = "questions",targetEntity = Answers.class, cascade = CascadeType.ALL)
private List<Answers> answers = new ArrayList<>();
public int getQues_id() {
return ques_id;
}
public void setQues_id(int ques_id) {
this.ques_id = ques_id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public int getMaxlength() {
return maxlength;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
public String getDependency() {
return dependency;
}
public List<Answers> getAnswers() {
return answers;
}
public void setAnswers(List<Answers> answers) {
this.answers = answers;
}
public void setDependency(String dependency) {
this.dependency = dependency;
}
}
Answers.java
#Entity
public class Answers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "ans_label")
private String ans_label;
#Column(name = "ans_value")
private int ans_value;
#Column(name = "ans_weightage")
private int ans_weightage;
#Column(name = "is_default")
private int is_default;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "ques_id")
private Questions questions;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAns_label() {
return ans_label;
}
public void setAns_label(String ans_label) {
this.ans_label = ans_label;
}
public int getAns_value() {
return ans_value;
}
public void setAns_value(int ans_value) {
this.ans_value = ans_value;
}
public int getAns_weightage() {
return ans_weightage;
}
public void setAns_weightage(int ans_weightage) {
this.ans_weightage = ans_weightage;
}
public int getIs_default() {
return is_default;
}
public void setIs_default(int is_default) {
this.is_default = is_default;
}
public Questions getQuestions() {
return questions;
}
public void setQuestions(Questions questions) {
this.questions = questions;
}
}
SaveApiController.java
#RequestMapping(value = "/saveData", method = RequestMethod.POST)
public void saveData(#RequestBody Questions questionss){
//questions.setAnswers(questionss.getAnswers());
saveQuestions.save(questionss);
}
The json data i am sending from postman looks like this.
{
"id": "31",
"question": "३. लिङ्ग ?",
"type": "input_spinner",
"description": null,
"param": "",
"maxlength": "0",
"dependency": null,
"answers": [
{
"ans_label": "पुरुष",
"ans_value": "1",
"ans_weightage": "0",
"is_default": "0"
},
{
"ans_label": "महिला",
"ans_value": "2",
"ans_weightage": "0",
"is_default": "0"
},
{
"ans_label": "अन्य",
"ans_value": "3",
"ans_weightage": "0",
"is_default": "0"
}
]
}
Questions and answers data are all being stored apart from foreign key column in answers table. the column "ques_id" is being stored as NULL.
One of the things that you have to keep in mind is that in order for the persistence provider to Cascade the save operation, you have to set the dependencies on both sides of the relationship..
So Quesions need to have a list of Answers and each of those answers need to have reference to the Questions entity. Only then the cascade will happen.
Not sure if this is the answer to your problem but give it a try.
i have two entity classes named Qa.java and Answeres.java
my Qa entity consists of lists of answers.
Qa.Java
#Entity
#Table(name = "qa")
public class Qa {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
private String question;
private String type;
private String description;
private String param;
private int maxlength;
#OneToMany(mappedBy = "qa", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Answers> answersList = new ArrayList<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public int getMaxlength() {
return maxlength;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
public List<Answers> getAnswersList() {
return answersList;
}
public void setAnswersList(List<Answers> answersList) {
this.answersList = answersList;
}
}
Answers.java
#Entity
#Table(name = "answers")
public class Answers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String ans_label;
private int ans_value;
private int ans_weightage;
private int is_default;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "question_id", referencedColumnName = "id",nullable = false)
private Qa qa;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAns_label() {
return ans_label;
}
public void setAns_label(String ans_label) {
this.ans_label = ans_label;
}
public int getAns_value() {
return ans_value;
}
public void setAns_value(int ans_value) {
this.ans_value = ans_value;
}
public int getAns_weightage() {
return ans_weightage;
}
public void setAns_weightage(int ans_weightage) {
this.ans_weightage = ans_weightage;
}
public int getIs_default() {
return is_default;
}
public void setIs_default(int is_default) {
this.is_default = is_default;
}
public Qa getQa() {
return qa;
}
public void setQa(Qa qa) {
this.qa = qa;
}
}
My controller from where i am trying to insert data.
TableDataController.java
#Controller
public class TabletDataController {
#Autowired
QaRepository qaRepository;
#RequestMapping(value = "/saveApiData", method = RequestMethod.GET)
public void saveApiData(){
Qa qa = new Qa();
qa.setParam("");
qa.setType("input_spinner");
qa.setDescription("");
qa.setQuestion("व्यक्तिको पहिलो नाम ?");
ArrayList<Answers> answersArrayList = new ArrayList<>();
Answers answers = new Answers();
answers.setAns_label("नेपाली");
answers.setAns_value(1);
answers.setAns_weightage(0);
answers.setIs_default(0);
answersArrayList.add(answers);
qa.setAnswersList(answersArrayList);
qaRepository.save(qa);
}
}
my qaRepository extends JpaRepository. so whenever i call this api i get an error of com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'question_id' cannot be null
what am i doing wrong?
You have a bidirectional OneToMany relationship, so you need to manually maintain both sides of the relationship. Here you are only setting the Qa side with qa.setAnswersList(answersArrayList);
You need to set the other side of your relationship manually. add:
answers.setQa(qa);
before you save your list
code as follow
public void saveApiData(){
Qa qa = new Qa();
qa.setParam("");
qa.setType("input_spinner");
qa.setDescription("");
qa.setQuestion("व्यक्तिको पहिलो नाम ?");
ArrayList<Answers> answersArrayList = new ArrayList<>();
Answers answers = new Answers();
answers.setAns_label("नेपाली");
answers.setAns_value(1);
answers.setAns_weightage(0);
answers.setIs_default(0);
answers.setQa(qa);
answersArrayList.add(answers);
qa.setAnswersList(answersArrayList);
qaRepository.save(qa);
}
when you save.you should Cascade save.Your annotations configure the relationship of the associated tables but also to associate them when they are saved
I have a Hibernate Entity "Intranet" which has this code:
// Imports removed
#Entity
#Table(name = "intranets", uniqueConstraints = #UniqueConstraint(columnNames = "company_name"))
#Cacheable
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Intranet {
#Id
#Column(name = "INTRANET_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private int intranetId;
#Column(name = "owner_id")
private int ownerId;
#Column(name = "setup_done")
private boolean isSetUp = false;
#Column(name = "company_name")
private String companyName;
#ElementCollection
#CollectionTable(name = "employees")
#Column(name = "employee")
private List<Integer> employeeIds;
public int getIntranetId() {
return intranetId;
}
public void setIntranetId(int intranetId) {
this.intranetId = intranetId;
}
public boolean isSetUp() {
return isSetUp;
}
public void setSetUp(boolean isSetUp) {
this.isSetUp = isSetUp;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getOwnerId() {
return ownerId;
}
public void setOwnerId(int ownerId) {
this.ownerId = ownerId;
}
public List<Integer> getEmployeeIds() {
return employeeIds;
}
public void setEmployeeIds(List<Integer> employeeIds) {
this.employeeIds = employeeIds;
}
public void addEmployee(int id) {
this.employeeIds.add(id);
}
public void removeEmployee(int id) {
this.employeeIds.remove(new Integer(id));
}
}
As you can see, I added two methods that don't directly are getters and setters but they're like convenience methods to have easy access to the collection and adding/removing employees.
When I call "addEmployee()" in my program, I am getting a simple NullPointerException. The question basically is how I can initialize the collection to not have null because I read that Hibernate uses internal implementations of collections and does not simply takes ArrayList.
Thanks for help in advance.
You have a NullPointerException because you have to initialize the list yourself. It does not matter which implementation you use. This will fix your problem:
#ElementCollection
#Column(name = "employee")
private List<Integer> employeeIds = new ArrayList<>();
How to join newMap detals in custMap.
Map<String, Customer> custMap= new HashMap<String,Customer>();
Map<String, DoCustomer> newMap= new HashMap<String,DoCustomer>();
for (Map.Entry<String, DoCustomer> cust: newMap.entrySet()) {
custMap.put(cust.getKey(),cust.getValue());
}
public class DoCustomer {
private Long id;
private String custName;
private String description;
private String status;
private List<DoCustomerBranch> doCustomerBranch=new ArrayList<DoCustomerBranch>
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
getter/setters of doCustomerBranch
}
#Entity
#Table(name = "CUSTOMER")
public class Customer implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private String custName;
private String description;
private String createdBy;
private Date createdOn;
private String updatedBy;
private Date updatedOn;
private Set<CustomerBranch> customerBranch=new HashSet<CustomerBranch>
#Id
#GeneratedValue(generator = "CUSTOMER_SEQ")
#SequenceGenerator(name = "CUSTOMER_SEQ", sequenceName = "CUSTOMERN_SEQ", allocationSize = 1)
#Column(name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "CUST_NAME",nullable=false)
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "CREATED_BY", length = 50)
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_ON")
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
#Column(name = "UPDATED_BY", length = 50)
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "UPDATED_ON")
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
#OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, fetch = FetchType.LAZY, mappedBy = "customer")
public Set<CustomerBranch> getCustomerBranch() {
return customerBranch;
}
public void setCustomerBranch(Set<CustomerBranch> customerBranch) {
this.customerBranch = customerBranch;
}
}
CustomerBranch
#Entity
#Table(name = "CUSTOMER_BRANCH")
public class CustomerBranch implements Serializable{
#Id
#GeneratedValue(generator = "CUSTOMER_BRANCH_SEQ")
#SequenceGenerator(name = "CUSTOMER_BRANCH_SEQ", sequenceName = "CUSTOMER_BRANCH_SEQ", allocationSize = 1)
#Column(name = "ID")
private Long id;
private String branchName;
private String branchAddress;
private Customer customer;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "BRANCH_NAME",nullable=false)
public String getBranchName() {
return branchName;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "MOBEE_CUSTOMER")
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
The problem with your code is that you want to put a DoCustomer in a Customer container. It only works if DoCustomer is a subclass of Customer.
Edit 1: You could use BeanUtils to convert a DoCustomer into a Customer. Here is a good tutorial.
Do you mean:
custMap.putAll(newMap)
As everyone else has pointed out, we need to know what DoCustomer is to be able to help.
But, from what you have given us, I'd suggest casting each DoCustomer to a Customer or, more correctly, making a new Customer from the fields of each DoCustomer.
Something like:
custMap.put(cust.getKey(), new Customer(cust.getValue().getId(), cust.getValue().getCustName(), and so on..));
inside your for loop.
I can see the customer class defined you have provided doesn't have a constructor, so naturally you would have to add one to it