user18544509
user18544509

Reputation:

How to write an Java Object that contains an arraylist of Objects to SQL database

I have a Student class:

public class Student implements Serializable{
    //each student has an arraylist of modules

    private String name = null;     //students name
    private int ID = 0;             //students ID number
    private String DOB = null;      //Students Date of Birth

    private ArrayList <Module> modules;         //creating the students module arraylist

public Student(String name,int ID, String DOB) {
    this.setName(name);
    this.setID(ID);
    this.setDOB(DOB);
    setModules(new ArrayList <Module> ());          //initialising the arraylist
}

Each student has many modules and the grade they got in each of these modules. I need to write these student objects to a Mysqln database but how would I store the arraylist of modules each student has in the student table?

Upvotes: 0

Views: 984

Answers (1)

Daniel Vilas-Boas
Daniel Vilas-Boas

Reputation: 896

Depends on how you intend to design your application, in case you'd like to follow a many to many relationship (each student has N modules and each module is being done by multiple students).

This kind of mapping can be done in two ways, unidirectional or bidirectional, it depends on how you plan to manipulate the entities or when there is an entity that is stronger.

There is no way you can store a list of modules inside the same student table unless you go to another kind of database (Mysql is relational) or would like to see a list of comma separated strings in a textual/blob column, my opinion is that this is a denormalized poor implementation.

Here is a code snippet you can try that will create a intermediary table to store the relationship between the entities.

@Entity
@Table(name="student")
class Student {

private long studentId;

@ManyToMany
    @JoinTable(name="student_modules", joinColumns=
    {@JoinColumn(name="student_id")}, inverseJoinColumns=
      {@JoinColumn(name="module_id")})
List<Module> modules;

}

@Entity
@Table(name="notebook")
public class Module {

 private long moduleId;
}

Upvotes: 1

Related Questions