Understanding Entity Modeling using 3 models in Hibernate - java

I am starting to learn Spring Boot and Hibernate by building small rest services.
I am using MySQL as my database.
I am able to understand relationship annotation used in hibernate though sometimes it's tricky to write with all the verbose syntax.
Right now I am struggling with how to map 3 entities together.
The following is what I am trying to achieve.
I have a teacher entity, a grade entity, and a section entity.
Now, each Grade can have multiple sections.
public class Grade {
private String name;
#OneToMany
private List<Section> sections;
}
public class Section {
private String name;
}
And, a teacher can teach in multiple grades or multiple sections of the same grade.
Imagine grade 1 to 5, each grade has section A to D.
Teacher, let's say John can teach Grade 1 (sec A, B) and Grade 2 ( sec C, D).
I am failing to understand the syntax to implement the above relationhip.
One way is to use another Entity called Class which will have grade and section as property.
public class Class {
private Grade grade;
private Section section;
}
another way can be to use a map data structure like Map<Grade, List<Section>> class;
Still, I am looking for help to write it down with JPA annotations.
Any lead is appreciated.

First of all I want to mention that your question is not specific to Hibernate, as you can solely rely on the JPA Specification for this task. However, Hibernate is the default ORM for Spring and will implement the JPA spec in your program by default.
Second, I do not think that you need separate database tables for Section and Grade, and they could be modeled as simple Java Enums. In the following I made a quick sketch of a class diagram (not DB Model!) that came to my mind.
Note that Grade and Section are Enums, to restrict entering corrupted values. In the database the Grade and Section object can be mapped as either ordinal or String, see here for reference. I would recommend persisting as String by using this annotation #Enumerated(EnumType.STRING). With regard to mapping the one to many relationship between teacher and class, I would recommend a bidirectional relation such as shown here. However, note that there are multiple ways to model this relationship in JPA. I hope I was able to help. Good luck!

Related

Modelling data and accessing it using the DAO pattern

I'm creating a very simple application in Java that will be storing questions in an embedded Derby database. I've decided to use the DAO pattern for accessing the data in the database. I cannot make use of an ORM for this project.
A question will have data that I would normally model using a many to one relationship in a relational database. An example of this data would be:
A question will have one category. One category will have multiple questions.
A question will have a score of 1000, 2000 or 3000. A score will have many questions.
With the above in mind, I would create three tables (brackets indicate columns):
Question (id, question, scoreId, categoryId)
Score (id, score)
Category (id, category)
My first question is:
Would modelling my data across three tables like I suggest above be bad practice/the wrong way to go about this? Is there any benefit in storing score and category in separate tables? Or would it be better to combine them into the Question table? A many to one relationship that links to a table with a single column (with the exception of id) seems redundant to me, as instead of storing an id referencing the Score/Category table, we can simply store the value of the category/score (since the category/score table does not store any additional information).
My second question is:
If modelling my data across separate tables is the correct approach, then how would I access the data using the DAO pattern? My confusion comes from the following:
I would create a DAO to populate a Question model object that would look a little something like this:
public class Question {
String question;
String category;
Integer score;
}
I would create a concrete implementation of the DAO interface like this:
public class QuestionAccessObject implements QuestionDao {
private static final String TABLE_1 = "QUESTION";
private static final String TABLE_2 = "SCORE";
private static final String TABLE_3 = "CATEGORY";
#Override
public List<Question> getAllQuestions() {
List<Question> questions = new ArrayList<>();
//Run a query with joins across the three tables and iterate over the result to populate the list
return questions;
}
}
Shouldn't each DAO object only be concerned with a single table in the database? My approach listed above doesn't seem like the most correct way to go about this. Seperate tables would also make inserting data into the database very messy (I don't understand how I could take clean approach using the DAO pattern and multiple tables). Creating a DAO for the Score and Category tables just wouldn't really make sense.. (and if I did this, how would I populate my model?)
Would modelling my data across three tables like I suggest above be bad practice/the wrong way to go about this? Is there any benefit in storing score and category in separate tables....?
It's a matter of discussion. In case of score I rather stick this information with the question. On the other hand, the category would be in the separated table since more of the question would share the same category, so it makes a perfect sense.
Shouldn't each DAO object only be concerned with a single table in the database?
Yes, DAO, an object should be concerned with a single source of data - as you say. I would certainly try to avoid any ComplexDao since those classes tend to get more complex and the number of methods increases over the time.
There exist a service layer to combine those results together and provide an output to the controller using the very same service.
Modeling the data across separate tables is A correct approach (not necessarily the best).
Separating tables helps database normalization: https://en.wikipedia.org/wiki/Database_normalization.
One could argue that the DAO pattern implies that each DAO object is concerned with a single entity . Similar to how ORMs work, an entity could easily reference other entities.
When you query for a question you could also just return the category and score ids inside the question object and force the library user to fetch the score value and category value (lazy fetch) using those id values with their respective DAOs (score and category).
So I believe that what you're doing seems fine
Hope this helps

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(){
}
}

Best Way to Design database for AutoComplete Functionality

Best Way to Design database for AutoComplete Functionality.
I have following usecase(using technologies JAVA,SPRING,HIBERNATE,Mysql):
I have Professional Details Which is Associated with Skills(Many to Many Relationship).
public class ProfessionalDetailsDTO {
private Integer professionalId;
//many to many
private List<SkillsDTO> profileSkills;
setter and getter ...
}
public class SkillsDTO {
private String skillName;
private Integer skillRating;
private Integer skillId;
setter and getter
}
Now From UI When I type Type Skills I should get the Valid Skills Suggestion (like JAVA,Hibernate).people might Save Dummy Skills or abrupt value
(e.g XYZ )in Skill Table ,So I don't Want to Show This as suggestion in autoComplete.
I Can Think of Following Approaches Right Now:-
Approach 1 : Having Four Tables as mentioned below
1.ProfessionalDetails
column:professionalId
2.Skills
column:SkillId,skillName,skillRating
3.Professional_Skills
column:skillId,professionalId
4. PreDefinedSkill
column:id,SkillName
Is it BestPractice to have one more table for preDefined Skills Which will be used for AutoSuggestion and The SkillName Fetched from the
predefined Table will be stored in the skills table?
Cons:SkillName Will be Duplicates in the Skills Tables.
Approach 2 : In this Approach SkillRating is Moved to professional_Skills Table and Skillname is unique in skillTable
Here I have to Map SkillDTO to Tables.I have to use annotaion Such as #secondaryTable.
1.ProfessionalDetails
column:professionalId
2.Skills
column:SkillId,skillName
3.Professional_Skills
column:skillId,professionalId,,skillRating
Approach 3 .Same as Approach 2 but instead of using hibernate annotation use query's to insert into professional_Skills table.
Please Suggest me Some Best Industry Practices To Implement the Above usecase
Thanks in Advance.
The Best Solution to Implement the Above use case(i.e Many to many with Additional Columns) is described in the Below Link:
http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany
Posting this as this might Help others.

Object-mapping in Spring JDBC?

I have previously used Hibernate and now I am trying to understand JDBC. I have done loads of research on Spring JDBC but still I could not understand how to create relationships between objects.
Assume I have a Product:
public class Product {
private Long id;
private String nam;
private Customer customer;
//constructor, getters and setters.
}
and a Customer:
public class Customer {
private Long id;
private String name;
private List<Product> products = new ArrayList<Product>();
//constructor, getters and setters
}
The relationship between Customer and Product is #OneToMany.
How to correctly save the product and customer objects in the db using SpringJDBC?
Thank you
It make a lot of sense in quite a few cases to not use a full blown ORM but rely on lower level of abstraction, like Spring JDBCTemplate and RowMapper. iBatis comes to mind as well. And that make sense even in large enterprise solutions.
If you leave the full blown ORM world, you will have to do additional work yourself. For example, you can write an SQL query with a join, returning all customer fields and all products of that customer, and iterate through it to map all that to Java object. In quite a few cases, the code can be as clean as what you would have with an ORM.
Writing all that data is more messy, especially if you need to optimize for stuff that has not been dirtied.
Best use case I can think of is batch processing, where control over data access becomes more important and higher level of abstraction do not necessarily make you more productive.
If you are willing to consider something other than spring or hibernate, sormula can do what you describe. See the one to many example. If you name the foreign key on the many side the same as the primary key on the one side, then you don't need any annotations.
To store a reference to one-side object (Customer) in the many-side objects (Products), you can use the OneToManyCascade#foreignKeyReferenceField. For examples, search the tests in the project for "foreignKeyReferenceField".
If I understand your question correctly, if think if you are not using ORM you would have to do this manually.
In your DAO class for Customer it would first have to persist all the products.
An alternative might be to create a Stored Procedure on the database and have that sort out the correct persistence.
This can be handled very nicely by Spring JDBC, the downside is you know have to manage Java and Stored Procedures.
In your case it might still be two Stored Procedures.
There is also the possibility that QueryDSL and Jooq, thought I haven't had a chance to have a good look at them.
I personally like the Stored Procedure solution, for me the additional over head is worth it, I know others disagree, but I just don't like/buy the ORM deal.

Categories