Bidirectional collection in java - 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.

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.

Making a simple UML class diagram for a school

I'm trying to create a simple class diagram for a school. Within my class-hierarchy, a school typically consist of two main stakeholders (student & teacher) and many students can be assigned to a teacher. May I know how I can show this relationship?
I have used aggregation and enumeration in my class diagram however, I'm not exactly sure if it's correct. Could you please advise me?
Multiplicity: The way you are using multiplicities is correct (as I can foresee it). It means that there must be at least one student per teacher. Without student, there is not teacher. Sounds like a hire and fire school with no permanent teachers.
Aggregation: You may use the shared aggregation (open diamond) the way you did. It's correct but see my remarks below.
Enumeration: Regarding the <<enumeration>> you would just need a dependency rather than an association. Unlike relations to classes an <<enumeration>> is kind of a "primitive" which is not represented as object.
Role names: As #Oguz points out it's a good idea to use role names at the end of the associations. So you would put teacher near Teacher and students (plural because you have 1..*) near Student at the association. These roles would be implemented as attributes.
Additional remarks on shared aggregation:
You must not care much about shared aggregation. As per UML specification it has no common semantics (p. 110 of UML 2.5):
Indicates that the Property has shared aggregation semantics. Precise semantics of shared aggregation varies by application area and modeler.
Aggregation is more about lifetime of objects and real life applications are rather rare than often (mainly if you have to be memory aware in terms of cost or security).
So in your (and most other) case(s) the multiplicity is what you want to show. This is usually more important than showing e.g. a composite aggregation (where the child objects dies with its parent) let alone shared composition.
You can change the aggregation name to students. And In the java code, teacher class has an array, arraylist or set etc. which name is students. And there is one more thing, is this relation 1 to many or 0 to many(0..*)?
public class Teacher extends StakeHolders{
public Student[] students;
public void markAttendance(){
}
}

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)

Java: How to insert a N:M association table

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.

On abstract classes in Java and Hibernate annotations

I am planing to create an application relying on DB using Hibernate. I will have some similar classes like teacher and student and so on. In DB they will have some fields with similar names. So I wonder If I can create a class Human with annotations for standard fields like Name, SName and so on so to just extend that class in teacher student and so on. Will it work? Does any one use it in such way?
I would suggest that teacher and student are not subclasses of human, but rather are roles that a human can play. If you make them subclasses then you are effectively saying that teacher can never be a student and vice versa.
Also, if one goes from being a student to teacher (or vice versa) then you lose any associations and history for that object.
Consider roles instead. Consider composition and delegation instead of inheritance in this example.
Take a look at Peter Coad's book: Java Design for more on this.
Also, you do want to think about the table implementation if you do decide to use inheritance: single table (with null cols for the subtype attribs) separate table or single table for super class and separate tables for subclasses.
Hibernate has extensive support for different scenarios involving inheritance and polymorphism. See the documentation
http://docs.jboss.org/hibernate/stable/core/reference/en/html/inheritance.html
The short answer is, yes you can do exactly what you want -- create a base class with fields common to subclasses. How hard/involved it is depends on how you structure the tables.

Categories