Request Body multiple parameters in springboot using object wrapper not working - java

I have 2 classes Student and Finals.
Student.java
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Student {
#Id
private int id;
private String name;
private int marks;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String name, int marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
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 int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
}
Finals.java
#Entity
public class Finals {
#Id
private int id;
private int marks;
private int totalMarks;
public Finals() {
super();
// TODO Auto-generated constructor stub
}
public Finals(int id, int marks, int totalMarks) {
super();
this.id = id;
this.marks = marks;
this.totalMarks = totalMarks;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public int getTotalMarks() {
return totalMarks;
}
public void setTotalMarks(int totalMarks) {
this.totalMarks = totalMarks;
}
}
ObjWrapper.java
public class ObjWrapper{
private Student student;
private Finals finals;
public ObjWrapper() {
super();
// TODO Auto-generated constructor stub
}
public ObjWrapper(Student student, Finals finals) {
super();
this.student = student;
this.finals = finals;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Finals getFinals() {
return finals;
}
public void setFinals(Finals finals) {
this.finals = finals;
}
}
I would like to take the marks of a particular student from student class and add some marks given by user and update it in the marks column of the Student.
I would also like to add a new row to finals table with id,marks,newmarks.
My code
#Autowired
public StudentRepo studentrepo;
#Autowired
public StudentService stuservice;
#Autowired
public FinalsRepo finalsrepo;
#PutMapping("/updatemarks/{id}/{marks}")
public void putTables(#RequestBody ObjWrapper wrapper,#PathVariable(value = "id") int id,#PathVariable(value = "marks") int marks) {
Student student = wrapper.getStudent();
student = studentrepo.getOne(id);
int studentMark = student.getMarks();
int newMarks = studentMark + marks;
Finals f = wrapper.getFinals();
f.setId(id);
f.setMarks(marks);
f.setTotalMarks(newMarks);
finalsrepo.save(f);
student.setMarks(newMarks);
studentrepo.save(student);
}
Error :
"message": "Required request body is missing: public void com.example.demo.controller.MainController.putTables(com.example.demo.entities.ObjWrapper,int,int)",
"path": "/updatemarks/1/50"
I am not able to unwrap through object mapper I think, I dont know what is wrong in my code...can anyone help me out....Thanks

Related

UML with subclasses

public class Student {
private String name;
private long id;
private String grade;
private int[] test;
private int NUM_TESTS;
public Student(){
name="Un";
id=0;
grade="Un";
test=new int[0];
NUM_TESTS=5;
}
public Student(String x, long z) {
name=x;
id=z;
}
public void setName(String n) {
name=n;
}
public void setID(long i) {
id=i;
}
public void setGrade(String g) {
grade=g;
}
/*public void setTestScore(int t,int s) {
test=t;
test=s;
}
public int getTestScore(int) {
return test;
}*/
public int getNumTests() {
return NUM_TESTS;
}
public String getName() {
return name;
}
public long getID() {
return id;
}
public String getGrade() {
return grade;
}
public String toString() {
return getTestScore()+getNumTests()+getName()+getID()+getGrade();
}
/*public void calculateResult() {
int sum=0;
for (int t:test)sum+=t;
double average= 1.0t*sum/5;*/
}
}
Here is my code I have spaced out the places where I am having the issues. I am writing a Student subclass with subclasses undergrad and postgrad.
Here is the UML
I don't understand how to correctly implement testScore if it is not one of the variables? Nevermind the calculate result I'll fix that myself. I am also unsure if my constructors are accurate. All the students do five exams that's a constant
setTestScore(int t, int s)... I do recommend to use carefully chosen names (identifiers). For example if you just rename the parameters to: setTestScore(int testNumber, int score) you can be more familiar what should you inplement.
test = new int[0];isn't what you want. You want test = new int[NUM_TESTS]
Try to reconsider method setTestScore(int testNumber, int score)
first parameter is actually the index in the array of test and the second is the value.
So, your method should be something like this:
public void setTestScore(int testNumber, int score) {
test[testNumber] = score;
}
I just gave you some guidance for your own implementation...
First of all, It seems that Student class should be abstract. because each student is UnderGraduate or PostGraduate.
Secondly, you should extend the child classes from Student class.
I hope the below code be helpful:
abstract class Student {
private String name;
private long id;
private String grade;
private int[] test;
private final int NUM_TESTS = 5;
public Student(){
name = "UN";
id = 0;
grade = "UN";
test = new int[NUM_TESTS];
}
public Student(String name, long id){
this.name = name;
this.id = id;
}
#Override
public String toString() {
//TODO: write your desire toString method
return getNUM_TESTS()+getName()+getId()+getGrade();
}
abstract void claculateResult();
public int getTestScore(int testNumber){
if(testNumber >= NUM_TESTS)
return 0;
return test[testNumber];
}
public void setTestScore(int testNumber, int score){
if(testNumber >= NUM_TESTS)
return;
test[testNumber] = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public int[] getTest() {
return test;
}
public void setTest(int[] test) {
this.test = test;
}
public int getNUM_TESTS() {
return NUM_TESTS;
}
}
and the UnderGraduate class would be:
public class UnderGraduate extends Student{
public UnderGraduate(){
}
public UnderGraduate(String name, long id){
super();
}
#Override
void claculateResult() {
//TODO: DO whatever you want
}
}
remember that the PostGraduate class is same as UnderGraduate.

using class object to initialize variable from 1 package to another but it is not accessable in java

my class.java content
package pkg1;
import pkg2.*;
public class myclass {
public static void main(String[] args) {
// TODO Auto-generated method stub
student stu = new student();
stu.getName("go");
}
}
contentof student.java
package pkg2;
public class student {
public int id;
String name;
int rollno;
int age;
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 int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
I want to initialize variable of student.java of pkg 2 from myclass.java
but its showing field is not visible i have imported contents of pkg2 in pkg1 myclass.java and also have declared the member function of student.java as public
How did you know it is not accessible? Did you encounter any error statement saying this? Take this as a rule of thumb to read the errors accurately before jumping to conclusions.
Try putting this in you main function.
student stu = new student();
stu.setName("go");
System.out.println(stu.getname());
Set the name using the setter first. Only then will you be able to get the name via the getter.
BTW you need to learn a lot of coding Java conventions as well. Like classnames should be starting with a capital. student -> Student.
I'm not completely sure what you're asking here, but first as pointed out by several of the comments to your question you cannot pass any arguments to getName() as it doesn't take any arguments. Secondly, as also pointed out in the comments, please conform to the Java naming convention.
package pkg1;
import pkg2.*;
public class MyClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu = new Student();
stu.setName("go");
//Verify the name's been set
System.out.println(stu.getName());
}
}
package pkg2;
public class Student {
private int id;
private String name;
private int rollno;
private int age;
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 int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

How to add data to different model class android

I'm newbie about android programming and Today I want to add data to another model class
and in another class model is same model
but I have no idea to add it
example
my first model
public class TelephoneModel {
private List<DataBean> data;
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and my second model
public class TelephoneDetailModel {
private List<DataBean> data;
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
and I have data in
List<TelephoneModel.DataBean> databeans = new ArrayList<>;
List<TelephoneDetailModel.DataBean> dataDetailbeans = new ArrayList<>;
and I want to add data databeans to dataDetailbeans
How to add it ,please give example for me,
thanks!
Hello change your model class like this (it is so simple to use)
--> TelephoneModel
public class TelephoneModel {
private String id;
private String name;
public TelephoneModel(String id,String name) {
this.id=id;
this.name=name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
--> TelephoneDetailModel
public class TelephoneDetailModel {
public TelephoneDetailModel(String id, String name) {
this.id = id;
this.name = name;
}
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
--> your activity
ArrayList<TelephoneModel> databeans = new ArrayList<>();
ArrayList<TelephoneDetailModel> dataDetailBeans = new ArrayList<>();
// add data into databean
databeans.add(new TelephoneModel("id-1", "name-1"));
databeans.add(new TelephoneModel("id-2", "name-2"));
// now add data databeans to dataDetailbeans
for (int i = 0; i < databeans.size(); i++) {
dataDetailBeans.add(new TelephoneDetailModel(databeans.get(i)
.getId(), databeans.get(i).getName()));
}
if any question then free to ask me...
Try this
List<TelephoneDetailModel.DataBean> databeans = new ArrayList();
TelephoneDetailModel.DataBean dataBean = new TelephoneDetailModel.DataBean();
dataBean.setId("1");
dataBean.setName("PREM");
databeans.add(dataBean);
TelephoneDetailModel.DataBean model1 = new TelephoneDetailModel.DataBean();
model1.setId("2");
model1.setName("PREM2");
databeans.add(model1);
TelephoneDetailModel.DataBean model2 = new TelephoneDetailModel.DataBean();
model2.setId("3");
model2.setName("PREM3");
databeans.add(model2);
TelephoneDetailModel.DataBean model3 = new TelephoneDetailModel.DataBean();
model3.setId("4");
model3.setName("PREM4");
databeans.add(model3);
for (int i = 0; i < databeans.size(); i++) {
Log.e("ID", databeans.get(i).getId());
Log.e("NAME", databeans.get(i).getName());
}
Out put
com.example.user33.demoapplication E/ID: 1
com.example.user33.demoapplication E/NAME: PREM
com.example.user33.demoapplication E/ID: 2
com.example.user33.demoapplication E/NAME: PREM2
com.example.user33.demoapplication E/ID: 3
com.example.user33.demoapplication E/NAME: PREM3
com.example.user33.demoapplication E/ID: 4
com.example.user33.demoapplication E/NAME: PREM4
Try this
public class TelephoneDetailModel {
private List<DataBean> data;
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String id;
private String name;
public DataBean() {
}
public DataBean(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
now to add data in your arraylist try this
List<TelephoneDetailModel.DataBean> databeans = new ArrayList();
databeans.add(new TelephoneDetailModel.DataBean("6","NEW NAME"));
DataBean in TelephoneModel class and TelephoneDetailModel is different, you can't add the Datadean to another list

Spring Data JPA ManyToOne Bidirectional

Problem: it works till i try to add Student obejcts to Database, but the tables are being created correctly .
I can't simplify the post any further. But it's mainly code that doesn't require a lot of reading, it's a simple spring data repository service model. I posted it all due to the fact idk what am i doing wrong. Problem is in the JPA mapping.
I got the example from over here http://www.java2s.com/Tutorial/Java/0355__JPA/OneToManyBidirectional.htm
MDOELS
#Entity
public class Department {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
#OneToMany(mappedBy="department")
private Collection<Student> students;
public Department() {
}
public Department(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String deptName) {
this.name = deptName;
}
public Collection<Student> getStudents() {
return students;
}
public void setStudent(Collection<Student> students) {
this.students = students;
}
public String toString() {
return "Department id: " + getId() +
", name: " + getName();
}
}
#Entity
public class Student {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
#ManyToOne (cascade=CascadeType.ALL)
private Department department;
public Student() {
}
public Student(String name, Department department) {
this.name = name;
this.department = department;
}
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 Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public String toString() {
return "\n\nID:" + id + "\nName:" + name + "\n\n" + department;
}
}
REPOSITORIES
#Repository
public interface DepartmentRepository extends JpaRepository<Department, Integer> {
Department findByName(String name);
}
#Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {
Student findByName(String name);
}
SERVICES
#Service
public class StudentService {
private final StudentRepository studentRepository;
#Autowired
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public void addToDatabase(Student student) {
this.studentRepository.saveAndFlush(student);
}
public Student getStudentByName(String name) {
return studentRepository.findByName(name);
}
}
#Service
public class DepartmentService {
private final DepartmentRepository departmentRepository;
#Autowired
public DepartmentService(DepartmentRepository departmentRepository) {
this.departmentRepository = departmentRepository;
}
public void addToDataBase(List<Department> department) {
this.departmentRepository.save(department);
department.forEach(this.departmentRepository::saveAndFlush);
}
public Department getDepartmentByName(String name){
return this.departmentRepository.findByName(name);
}
}
My main method
#Component
public class Terminal implements CommandLineRunner {
private final StudentService studentService;
private final DepartmentService departmentService;
#Autowired
public Terminal(StudentService studentService, DepartmentService departmentService) {
this.studentService = studentService;
this.departmentService = departmentService;
}
#Override
public void run(String... strings) throws Exception {
Department department = new Department("dep1");
Department department1 = new Department("dep2");
Department department2 = new Department("dep3");
Department department3 = new Department("dep4");
List<Department> departments = new ArrayList<>(Arrays.asList(department, department1, department2, department3));
this.departmentService.addToDataBase(departments);
//
Student student = new Student("pesho", department);
Student student11 = new Student("gosho", department1);
this.studentService.addToDatabase(student11);
this.studentService.addToDatabase(student);
student = new Student("sasho", department2);
this.studentService.addToDatabase(student);
// System.out.println(this.studentService.getStudentByName("gosho").getDepartment1());
// System.out.println("CHECKING ONE TO ONE BIDIRECTIONAL: " + this.departmentService.getDepartmentByName("dep1").getStudent());
}
}
So here when i try to add students in the students table it gives an error
The error is the fallowing
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: app.models.Department
you added cascade= CascadeType.ALL for Department in Student class and save departments separete. this.departmentService.addToDataBase(departments);
fix : dont call
departmentService.addToDataBase(departments);
or remove CascadeType.ALL from Student
Well I can't understand you problem completely but here's what I would like to add. Cascading for add operation is not implemented or it's incomplete. Hope it helps.

Hibernate mapping non-entity class with List

I have 3 classes - Patient, AllergyList and Allergy. Both Patient and Allergy are #Entity and AllergyList simply has a variable with a list of Allergiest.
#Entity
public class Allergy {
private String id;
private String name;
public Allergy(String i, String n) {
id=i;
name=n;
}
#Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String n) {
this.name = n;
}
}
The Allergy class MUST have an id, and is referenced by other class in my program.
public class AllergyList {
private List<Allergy> allergies = new ArrayList<Allergy>();
public List<Allergy> getAllergies() {
return allergies;
}
public void setAllergies(List<Allergy> a) {
this.allergies = a;
}
}
I need to have this class, because I have inherited the program, and cannot change the existing codebase.
#Entity
public class Patient {
private String id;
private AllergyList allergyList = new AllergyList();
public Patient() {}
#Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public AllergyList getAllergyList() {
return allergyList;
}
public void setAllergyList(AllergyList allergyList) {
this.allergyList = allergyList;
}
}
And the main...
public static void main(String[] args) {
Patient patient = new Patient();
patient.setId("100001");
List<Allergy> allergies = new ArrayList<Allergy>();
allergies.add(new Allergy("1","Dust"));
allergies.add(new Allergy("3","Apple"));
allergies.add(new Allergy("4","Bee"));
patient.allergyList.setAllergies(allergies);
.
.
session.save(patient);
.
.
}
So the above three classes are what I'm given. I need to create allergy_list table that contains the following:
allergy_list
patient_id
allergy_id
I know I can create a List inside the Patient class, but the way the program is written I need to access the Allergy through the AllergyList class. How can I annotate to make this happen? Is it even possible?

Categories

Resources