#Method to add new Subject
1 messages · Page 1 of 1 (latest)
<@&987246883653156906> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
public void addSubject(Integer id, Subjects subject) {
Optional<Student> studentOptional = studentRepository.findById(id);
studentOptional.ifPresentOrElse(student -> {subjectRepository.save(subject);}, ()-> {
try {
throw new StudentDoestNotExistException("Student is not found");
} catch (StudentDoestNotExistException e) {
throw new RuntimeException(e);
}
});
}```
im wondering if this is the correct way to do it
yea looks good
why not changing this {subjectRepository.save(subject);} to this subjectRepository.save(subject)
also why this:
try {
throw new StudentDoestNotExistException("Student is not found");
} catch (StudentDoestNotExistException e) {
throw new RuntimeException(e);
}
kinda new with lambda expressions i tried to do best i could, ill recheck and correct it😅
intellij proposed to add try/catch i just wanted to throw the exception
the second expression was supposed to be just the throw statement in ifPresentOrElse
not sure but I think you can change it even to this:
student -> {subjectRepository.save(subject);}
to
subjectRepository::save
its called method references
ah oki thanks for sharing ill read into it
is it supposed to be an alternative to lambdas?
"yes"
its more readable in many situations and technically also implemented more efficiently
its just a very short way of implementing a method of a functional interface
and method references are even shorter
yes it's just too short prolly makes sense a lot when you use it often
yeah. u have to become familiar with it
btw when using ifPresentOrElse, i wanna throw an exception and squid pointed out it might not be correct way of doing this
"if present or else throw" is the same as orElseThrow()
String name = maybePerson.orElseThrow().getName()
orElseThrow() either throws or returns the contained object if its present
its a getOrElseThrow(), essentially
so if u want to use getName() if its there and throw if its not there, u write what i wrote above
so in ur case that would look like:
Student student = studentRepository.findById(id)
.orElseThrow(() -> new StudentDoesNotExistException(id));
subjectRepository.save(subject); // use student somewhere? lol
regarding the exception, make it an unchecked exception and give it a constructor to accept the ID
ah oki
actually i don't want to add subject if a student doest not exist
that's why the check
it doesnt
it throws if the student wasnt found
so the method is aborted
exceptions stop the flow
oh no i thought you meant in comments //use student somewhere?
would it be more complicated if i wanna check if the sub already exists in there
and i would actually use existsById instead
if (!studentRepository.existsById(id)) {
throw new StudentNotFoundException(id);
}
subjectRepository.save(subject);
(no need to retrieve the object and use optional if u dont even intent on using the student)
👌
if i wanna make another check if sub exists or not then it would be a another nested if statement?
to avoid adding duplicate subjects
whats the ID on that repository?
it would just overwrite it then
wouldnt it?
like, if u have a subject with the same student ID, it would silently overwrite the old entry
ye maybe i could get all the subjects and iterate over it?
what do u want to do if there is already a subject with that ID?
throw? or just silently not do anything?
since im think a comparison by subject name would be more fitting
if a subject with same name exists, then i'd throw a user def exception
why subject with the same name and not work on its ID?
multiple students could have the same subject, couldnt they
so there have to be multiple "Math" entries
but with different student IDs
the ID on that repo, u said
we can grab all subjects of a particular stud
there's two tables
yeah but subjectRepository has an ID as well
ah
which is unique for each entry
i see
so u dont want a new math entry in that table
but its not possible to have 2 Math objects with different IDs, is it
the ID is part of the subject object
so when u do save, it looks under the subject-ID
two math subjects can not have say same studID which is fk for the table
wait isnt that unique for each entry, auto generated
yeah but its generated when u create ur object
and at this point in ur method u already have it
Subject subject
so im thinking: whats the problem with doing studentRepository.save(subject) again
it wouldnt change anything, would it
a student could add same subject, since im not passing in subID along with sub obj so it would basically add duplicate subjects for same student if i want to add
i dont fully follow. have u tried it? if so, can u show a screenshot of the database entries so that we can see the problem
i havent tried that part yet, ill give it a go and see if it creates a problem
thanks for help
update: changed the addSubject method as zabu suggested, when i try to add say a new subject with a same name it adds it to db
this is my subject table after calling the endpoint
updated addSubject method
pls do ping
and u dont want to add it again, even if the remaining values are totally different?
or overwrite the existing?
each subject is unique to each student
as you can see both maths subs have same studId, basically when say student with id 1 tried to add maths multiple times
yeah but those 2 entries are different
5, 3 vs 7, 3
so which one do u want
old or new
oh if i keep it same do you think it wont add it?
my question is: what do u want to achieve
u showed ur current DB
but what would be the expected DB
well it shouldnt add the subject and throw a exception because subject with such name already exists
okay
is there a reason u have the subId if u dont use it at all here?
like, why do both math objects have different IDs. that shouldnt be possible in the first place
is the ID part of the subject class or not?
u definitely have to index the subject name if u need to use it
i don't really have a need for subID, i assumed each table has its own unique index so i included it
how do u even get to a place where u end up having multiple math objects (despite the same student ID)
are you asking when this would happen?
package com.studentportal.student.subject;
import com.studentportal.student.Student;
import javax.persistence.*;
@Entity
public class Subjects {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="subid")
private Integer subId;
@Column(name="subname")
private String subName;
@Column(name="totalclasses")
private int totalClasses;
@Column(name="classesattended")
private int classesAttended;
//private Integer studentId;
@ManyToOne
@JoinColumn(name="studid")
Student student;
public Subjects(){}
public Subjects ( String subName, int totalClasses, int classesAttended, Student student){
//this.subId=subId;
this.subName=subName;
this.totalClasses=totalClasses;
this.classesAttended=classesAttended;
this.student=student;
}
public Integer getSubId() {
return subId;
}
public void setSubId(Integer subId) {
this.subId = subId;
}
public String getSubName() {
return subName;
}
public void setSubName(String subName) {
this.subName = subName;
}
public int getTotalClasses() {
return totalClasses;
}
public void setTotalClasses(int totalClasses) {
this.totalClasses = totalClasses;
}
public int getClassesAttended() {
return classesAttended;
}
public void setClassesAttended(int classesAttended) {
this.classesAttended = classesAttended;
}
@Override
public String toString() {
return "Subjects{" +
"subId=" + subId +
", subName='" + subName + '\'' +
", totalClasses=" + totalClasses +
", classesAttended=" + classesAttended +
'}';
}
public void setStudent(Student student) {
this.student=student;
}
public Student getStudent(){
return student;
}
}
this is my subject entity class, is it possible to use subName as index instead?