How to Pass Specific Pair from Hibernate Many-to-Many Relationship - java

I am setting up a Many-to-Many relationship similar to the example here: https://dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-many-to-many-using-annotations-1.html.
If I want to create another entity called Grade that contains a specific Student-Course pair, how can I do that? I know I can have Grade reference Student and Course individually, but that doesn't reference the STUDENT_COURSE table. Ideally I would be able to have a StudentCourse object in my Grade class, but I don't know how to do that without creating a StudentCourse entity myself.

Related

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)

Hibernate Mapping

I have an issue in performing Hibernate Mapping. The scenario is as follows:
There is a User class which has username, name, dateofbirth, image and other information pertaining to a user with username as the primary key.
Second class is Product class which has product id and other information related to a product with primary key as product key.
The third class is Order class which has OrderId, OrderDate, Username- should be foriegn key-referring to the User class username and finally a Set of type Product- because one order can have many products.
Now I want the primary key of the Order class as a composite key (OrderId, ProductID) and this productID should be reference from Product Class.
The relationships that I want to create are as follows:
1. One order can belong to only one User
2. One order can have many products
Can someone lead me on how to go about it? Any kind of help will be great.
I think most likely you are thinking similar relationship. Difference in your requirement is you need One to Many mapping from Order/PurchaseOrder to Product/Item and you don't want Shipment.
My suggestion would be:
Create bi-directional one-to-many relationship b/w User and Order. Benefit for bidirectional is you can access User Object from Order Object, if not required, you can keep it unidirectional from User to Order.
Create one-to-many relationship b/w Order and Product.
Instead of composite key in order, keep the primary key as just OrderID. You can still fetch list of products from your order object and order object from user object.
The whole point in making this decision is from which object you derive remaining objects. With ORMs you should know from which object you would derive rest and so my suggestion is based on assumption that you will have User object available as attached entity, so you can get list of orders (defined as set) and from a particular order find out list/set of Products.
In case you have Order object available first, then create a bidirectional with User. So that you can find list/set of Products at one end, and Customer associated at other.
For ORM mappings refer Hibernate Mapping Examples.
Hope this clarifies.

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.

Hibernate: #UniqueConstraint Across Multiple Tables?

I have a data model in which a number of entities inherit some common attributes from a single superclass entity. I am using InheritanceType.JOINED on the superclass, which causes Hibernate to create a single table for attributes defined in the superclass, with subclass tables containing only columns that are added by the subclass (so to load the attributes for a subclass instance, a join is performed between the two tables). That is all working fine.
What I'd like to do, however, is specify a unique constraint that includes fields in both the subclass and superclass tables. For instance, say that my superclass entity is something like:
Thing: {id, name}
...and then I have some subclass entities like:
Company: {address} //inherits 'id' and 'name' from 'Thing'
Employee: {company} //inherits 'id' and 'name' from 'Thing'
...and I want to configure Hibernate to automatically enforce that a given Company cannot have two Employee's with the same name. The company field is in the Employee table, but the name field is in the Thing table, so is there any way to get Hibernate to enforce this constraint, or do I need to do it programmatically whenever I add a new Employee?
If it's not possible in the Database it won't be possible with Hibernate. You can't create one constraint on multiple tables with SQL so neither in Hibernate.
You could work around this by creating a new Entity holding only the company and employee id and setting a unique constraint on those 2 fields but I would recommend enforcing this programmatically.
You could not use InheritanceType.JOINED, then everything ends up in a huge table, and you could write your constraint. As said before: What you want is just not possible in a relational DB.

ORM model and DAO in my particular case

I have the DB structure as follows:
table STUDENT (say, id, surname, etc)
table STUDENT_PROPERTIES (say, name_of_the_property:char, value_of_the_property:char, student_id:FK)
table COURSE (id, name, statusofcourse_id)
table STATUSOFSOMETHING (id, name_of_status:char ('active','inactive','suspended' etc))
table STUDENT_COURSE (student_id,course_id,statusofsomething_id)
Let's try to pick up domain objects in my database:
Student and Course are main entities.
Student has a list of courses he attends, also he has a list of properties, that is all for this student.
Next, Course entitity. It may contain a list of students that attend it.
But in fact, the whole structure looks like this: the starting point is Student, with it's PK
we can look a list of his properties,
then we look into the STUDENT_COURSE and extract both FK of the Course entity and also the Status
of the combination, it would look like "Student named bla bla, with all his properties,
attends math and the status of it is "ACTIVE".
now, quotation
1) Each DAO instance is responsible for one primary domain object or entity. If a domain object has an independent lifecycle, it should have its own DAO.
2) The DAO is responsible for creations, reads (by primary key), updates, and deletions -- that is, CRUD -- on the domain object.
Now, first question is
What are entities in my case?
Student, Course, Student_Course, Status = all except for StudentProperties?
Do I have to create a separate DAO for every object?
The entities you will need to create are:
Student
StudentProperties
Course
CourseStatus (not really necessary as you could use an enumerated field in Course instead)
StudentCourse doesn't need to be created, as you can just use a Many-to-Many mapping in Hibernate and it will give you a nice set of courses in your Student object.
Here's a great tutorial on hibernate mapping that does pretty much everything you need:
http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping-many-to-many-1.html

Categories