#Method to add new Subject

1 messages · Page 1 of 1 (latest)

left sail
#

My method addSubject()'s goal is to add a new subject to db, first it checks whether a particular student exist only then it proceeds to save the subject otherwise it throws a user defined exception StudentDoesNotExistException

raw mothBOT
#

<@&987246883653156906> please have a look, thanks.

raw mothBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

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.

left sail
#
  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

solar compass
#

yea looks good

heavy flower
#

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);
            }
left sail
left sail
#

the second expression was supposed to be just the throw statement in ifPresentOrElse

heavy flower
left sail
#

what's this called btw i remember seeing it somewhere

#

part of java 8?

heavy flower
heavy flower
left sail
#

ah oki thanks for sharing ill read into it

#

is it supposed to be an alternative to lambdas?

foggy prawn
#

"yes"

#

its more readable in many situations and technically also implemented more efficiently

left sail
#

lambdas def look confusing to me

#

ill try to use it instead

foggy prawn
#

its just a very short way of implementing a method of a functional interface

#

and method references are even shorter

left sail
#

yes it's just too short prolly makes sense a lot when you use it often

foggy prawn
#

yeah. u have to become familiar with it

left sail
#

btw when using ifPresentOrElse, i wanna throw an exception and squid pointed out it might not be correct way of doing this

foggy prawn
#

"if present or else throw" is the same as orElseThrow()

left sail
#

but i only pass in the else part in there?

#

let me look at orElseThrow

foggy prawn
#

String name = maybePerson.orElseThrow().getName()

left sail
#

oh when maybePerson is valid it accepts it

#

otherwise calls getName()

foggy prawn
#

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

left sail
#

ah oki

#

actually i don't want to add subject if a student doest not exist

#

that's why the check

foggy prawn
#

it doesnt

#

it throws if the student wasnt found

#

so the method is aborted

#

exceptions stop the flow

left sail
#

oh no i thought you meant in comments //use student somewhere?

foggy prawn
#

ah okay

#

then the variable is obsolete

#

but yeah

left sail
#

would it be more complicated if i wanna check if the sub already exists in there

foggy prawn
#

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)

left sail
#

this looks a lot cleaner

#

oki got it use optionals when intend to use the obj

foggy prawn
#

👌

left sail
#

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

foggy prawn
#

whats the ID on that repository?

left sail
#

it's student id

#

each student a few subjects

foggy prawn
#

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

left sail
#

ye maybe i could get all the subjects and iterate over it?

foggy prawn
#

what do u want to do if there is already a subject with that ID?

#

throw? or just silently not do anything?

left sail
#

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

foggy prawn
#

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

left sail
#

subject table would have multiple math entries true

#

but the fk is student id

foggy prawn
#

the ID on that repo, u said

left sail
#

we can grab all subjects of a particular stud

left sail
foggy prawn
#

yeah but subjectRepository has an ID as well

left sail
#

yes

#

subID

foggy prawn
#

ah

left sail
#

which is unique for each entry

foggy prawn
#

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

left sail
#

two math subjects can not have say same studID which is fk for the table

foggy prawn
#

yeah but subject-ID

#

its the same

left sail
#

wait isnt that unique for each entry, auto generated

foggy prawn
#

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

left sail
#

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

foggy prawn
#

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

left sail
#

i havent tried that part yet, ill give it a go and see if it creates a problem

#

thanks for help

left sail
#

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

foggy prawn
#

or overwrite the existing?

left sail
#

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

foggy prawn
#

yeah but those 2 entries are different

#

5, 3 vs 7, 3

#

so which one do u want

#

old or new

left sail
#

oh if i keep it same do you think it wont add it?

foggy prawn
#

my question is: what do u want to achieve

#

u showed ur current DB

#

but what would be the expected DB

left sail
#

well it shouldnt add the subject and throw a exception because subject with such name already exists

foggy prawn
#

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

left sail
#

i don't really have a need for subID, i assumed each table has its own unique index so i included it

foggy prawn
#

how do u even get to a place where u end up having multiple math objects (despite the same student ID)

left sail
#

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?