Java: How to insert a N:M association table - java

I'm wondering what would be the best algorithm (couldn't find any java best practices documentation about this) to insert data in a association table from a N:M relationship.
For Example, a many to many relationship like "a teacher has many students and a student has many teachers" that requires a association table like Teacher_Student with the three usual fields like teacher_id, student_id and date.
In my case I keep, for not-db-related reasons, an array with the teachers in the student object and viceversa, an array of students in the teacher object.
What do you guys think is the best java algorithm to insert this in sql?
Any pseudocode or a link to some documentation would be great. Thank you all for your advice.

for each student s
for each teacher t in the s array of teachers
insert t, s, date
Of course, this could equally well be done the by iterating over the teachers, inserting a record for each student in the teacher's array of students. That is a symptom of the non-normalized form of the internal data.

Related

Modeling circular depedencies

I am trying to model down the relationship between student and course. Below are the 2 high level queries i need to support down :
Finding all the courses a student is enrolled in
Find all the students enrolled for a course.
The relationship is a M:N relation ship (many to many, i.e. multiple students enroll to multiple courses).
How can i model them in terms of java objects. Intuitively, Student and Course seem to refer each other, creating circular dependency (or back reference).
class Student{
Long id
String name
List<Course> enrolledCourses;
Long rollNumber
}
Course{
Long id
String name
List<Student> enrolledStudents;
}
Is it the right behaviour to model such requirements in the above manner.
I am a little hesitant to create such circular dependencies, but not sure how i can model it otherwise.
Is above the right approach ?
Or does there exist a better way to model these sort of behaviour's ?
If I understand you correctly you're a bit afraid of the redundancy. If Student X visits Course Y, you have Course Y in the student's list of courses and Student X in the course's list of students.
If you pay attention to the modifying methods, this will probably be the best way to model this situation.
But if your fear of ending up with a student visiting a course he wasn't in (according to the course), you'll have to do it like in relational databases and create a relation object.
Now if you think a little more about the situation, there's probably a lot to tell about this course-visit. When did the student visit the course? Did he do any exams? what were the results? Which professor lead this instance of the course? After analysing that, you'll have a much better picture of the situation.
My approach is usually to analyse the situation thoroughly first. Then I analyse my operations on the data. Finally I start thinking about an optimal representation of my data.
This is without problems in Java, and the right approach. A bijective relation, being regularly used in both directions. In JPA they would typically get an annotation to fetch them lazily.
In fact modeling with JPA annotations would allow you to express primary key, many-to-one and such.
I personally would prefer long rollNumber instead of the nullable Long rollNumber.
Of course not always a sensible thing to do, especially when the entities are subordinate.

Sql to object, many to many with field

I am working on a little website. The database was created and we need to create objects from sql now.
Usually, in "Many to many" relation, I use a list to represent this relation. (List of ingredient in recipe, and if I need, a list of recipe in ingredient).
But I don't know what is the best way when the junction table contain field.
For example with theses tables:
###### #################### ##########
RECIPE INGREDIENT_IN_RECIPE INGREDIENT
id id_ingredient id
name id_recipe name
quantity
other
Is there a best way to create object from this sql?
I don't know if:
I need to create an third object "IngredientInRecipe". And list it on recipe/ingredient?
Maybe create fields quantity/other in ingredient and use it only when I want to handle ingredient as "ingredientinrecipe"?
Or create a Subclass of Ingredient with quantity/other?
Maybe I'm totally wrong and I just have to create list in recipe and use sql query or array for other things but I'm little bit lost.
This is a simple association class and you would model it like this:
You concrete object model with single tables it pretty fine.
The answer here is based on the question is the INGREDIENT_IN_RECIPE an entity by itself, or is it just a relational table to create the many to many in the db.
Currently, INGREDIENT_IN_RECIPE contains additional information, that is really important and further specifies the relation between RECIPE and INGREDIENT, so this qualifies it is a proper entity.
IMHO, the best way here is to create a entity class for the INGREDIENT_IN_RECIPE table and list it on the RECIPE entity class at least. You need to check if the relation from the INGREDIENT entity is really needed and useful.

Java DB: bind multiple instances of a class to one instance of another class

I don't really know how to describe this problem (as you tell by the dodgy title), so here's a full description of the problem.
I have two classes, Teacher and Class.
Each teacher can teach to several classes and each class has several teachers.
In Java, we've mapped it like this:
public class Class {
#ManyToMany(mappedBy = "classes")
private List<Teacher> teachers = new ArrayList<>();
}
We have a superclass, User, and two subclasses, Teacher and Student. These classes inherit from the User superclass. So, in our database we have a table called Users which stores all users as teachers or students.
Now, students can only be in one class, so they can only have one ClassID stored in the database.
But as I said before, teachers can have several classes. So the point is : How am I able to store all the classes that a teacher has in the database?
I see Java created an extra table, called User_Class, which is probably ment to store all the different classes a teacher has and vica versa. Problem is that I can't find any documentation about how to work with this.
Can someone please give me a hand here?
Thanks in advance.
Before trying to solve this by code, I think you need to understand it from the database point of view.
You are trying to build a many-to-many relationship. This sort of relationship is built by splitting it in two one-to-many relationships.
So, if you have two entities (namely Course and Teacher... I avoid using "classes" to prevent confusion), and one Course can have many Teachers and one Teacher can have many Courses, then a way to create the relation (in the database) would be like this:
Table Courses
courseId (PK)
courseName
Table Teachers
teacherId (PK)
teacherName
Table Courses_Teachers
courseId (FK, PK)
teacherId (FK, PK)
(PK stands for "primary key", and FK stands for "foreign key")
Hope this little introduction helps you visualize the way to solve your problem.
That approach is based on a composite primary key.
This link is about that:
how to make a composite primary key (java persistence annotation)

access data from table in many to many relationship in hibernate

I have three table's student , course , student_course
table student
{
student_id(PK)
}
table course
{
course_id(PK)
}
table student_course
{
student_id(PK+FK)
course_id(PK+FK)
}
I created model class's and configuration files using Hibernate Generation Tool.
It create following files-
1) student.java & student.hbm.xml
2) course.java & course.hbm.xml
And for student_course it creates set in each hbm file with Many-to-Many relationship.
So I want Course object's related to student, for this i want to access student_course table separately.
Right Now i access Course object related to student by accessing set of student_course through student object.I think it is not efficient one.
What is the efficient way to this?
Can i do this
by writing sql query or
by manually creating studentCourse.java & studentCourse.hbm.xml
please suggest me efficient way to access course object's related to student object.
please suggest me efficient way to access course object's related to
student object.
I think what you've got it the right approach. There is a link table but Hibernate has hidden it through the use of a ManyToMany - this is the correct modelling for this relationship. A student can take many courses and a course has many students.

Bidirectional collection in java

I have Many-to-Many associated entities information with me.
I would like to show the user the list of "students" and if user chooses an student, show his teachers.
Conversely, user may opt to see list of teachers and he/she can select a teacher to see all the students that teacher is teaching.
I am looking to have a java collection class (java built in or 3rd party) to represent such data so that I can query for teachers based on student or vice versa.
Bidi map comes quite close but it enforces 1:1 relationship. I have many to many relationship.
Any clues?
i think you couldn't do that with a map. the most simple way would be, to create a Student class and a Teacher class. both of it could have a method like addTeacher(Teacher teacher) / addStudent(Student student). So each Student objects knows it Teachers and each Teacher object knows it Student.
I am not sure if this is what you are looking for, but you can have a look at Guava BiMap
Does this not suffice?
Map<Student, Set<Teacher>> studentsToTeachers;
Map<Teacher, Set<Student>> teachersToStudents;
It's not a single collection, but it would solve your problem, provided your implementation was correct.

Categories