I have 4 tables:
Teacher, Student, Course and their common join table TeacherStudentCourse.
The first three tables all have one to many relationship with the last table.
Here is a screenshot from my DB DataBase sample
Hence, for example, I should be able to get the desire Students by providing Teacher ID and Course ID.
I had previously asked a question on join table. Previous Question
And I do get the answer.
I was trying to improve based on the previous codes
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<Object> list = session.createQuery("select s from Student s join s.teacherStudentCourses tsc where tsc.teacher = :teacher and tsc.course = :course")
.setParameter("teacher", teacher)
.setParameter("course", course)
.list();
session.getTransaction().commit();
session.close();
But I do not seem to get it working after countless tries. Maybe the query just cannot create in that way? Any helps will be appreciated!
[UPDATE]
The error I get is:
org.hibernate.QueryException: could not resolve property: teacherStudentCourses of: model.Student [select s from model.Student s join s.teacherStudentCourses tsc where tsc.teacher = :teacher and tsc.course = :course]
Here tables are associated to each other with foreign key so all child table (teacher,cource,student) should have a parent type variable in their POJO.
Let this is "TeacherStudentCource tsc" in Student.class.
Now the query will be..
select s.studentId,s.name,s.gender,s.birthdate, from Student s inner join s.tsc b where b.teacherId=:tid and b.courceId=:cid;
Teacher ID=tid
Course ID =cid
Related
I am trying to join two entities in a third one using #Query method.
#Query("SELECT new com.concretepage.entity.DeptEmpDto(d.departmentId,d.departmentName,d.managerId,d.locationId,e.employeeId,e.firstName,e.lastName,e.phoneNumber,e.hireDate,e.jobId,e.salary,e.commissionPct) FROM Employee e INNER JOIN Department d")
List <DeptEmpDto> fetchEmpDeptDataInnerJoin();
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1.
I cannot understand where is my mistake.Any help will be appreciated :).
You missed the joining condition after joining tables using ON clause. So just change your query with this:
#Query("SELECT new com.concretepage.entity.DeptEmpDto(d.departmentId,d.departmentName,d.managerId,d.locationId,e.employeeId,e.firstName,e.lastName,e.phoneNumber,e.hireDate,e.jobId,e.salary,e.commissionPct) FROM Employee e INNER JOIN Department d on e.joining_column_from_table1=d.joining_column_from_table2")
Make sure to replace joining_column_from_table1 and
joining_column_from_table2 with your column names from table
Employee and Department respectively
I have a hql request which looks like:
select Distinct prof
from Professor as prof
left join fetch prof.students as stud
Professor and Student are in a manytomany relation.
I would like to order prof list by student's name.
I tried :
select Distinct prof
from Professor as prof
left join fetch prof.students as stud
order by prof.students.name
I got the error:
SEVERE: org.springframework.orm.hibernate3.HibernateQueryException: illegal attempt to dereference collection
I also tried:
select Distinct prof
from Professor as prof
left join fetch prof.students as stud
order by stud.name
I got the error:
SEVERE: org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query;
Is my order by clause possible? Or the hibernate mapping doesn't allow such request?
Remove the Distinct keyword from your query. Then, if you need to eliminate duplicates, use a ResultTransformer to consolidate the result set for you.
String hql = "select prof from Professor as prof left join fetch prof.students as stud order by stud.name";
Query query = session.createQuery(hql)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
I am new to hibernate so I am pretty sure that some of you would be amused by this question. It has been driving me crazy. This is a hibernate query question.
I have two tables, Assuming one is outlet and one is flyers
outlet - outlet name,outlet address, merchantName
flyers - flyerId, flyerName, merchantName
so flyers belong to a merchant and a merchant has many outlets etc,
using hibernate, to get a simple query like to get the different outlets from the outlet table using the merchantName, I use the code:
public List<Outlet> getDealOutlet(#PathParam("merchant") String merchant) {
some code here....
outletsList = session.createQuery("from Outlet as outlet where outlet.merchantName = :merchant").setString( "merchant", merchant ).list();
some code here
}
And that works.
My question is how do I return the lists of outlets for a particular flyerId.
Any help is appreciated thanks
Is the question "How can I return the list of outlets for the merchant associated with a particular flyerId?"
If so, do you have a table merchants that's mapped to a class Merchant? That's the path to go down; Hibernate can easily let you query across joins, but if Hibernate doesn't know about the join because all you've got is a magic String called merchantName that you know happens to be the same in the two tables, then Hibernate can't help you out.
(Though of course you could run two queries, but I doubt that's what you're looking for.)
It depends on your mappings, if there is an Merchant entity, and both other entities have an association to it, it can be written as:
select o
from Outlet o
join o.merchant m
join m.flyers f
where f.id = :flyersId
Other wise you can do something like you do in SQL:
select o
from Outlet o, Flyers f
where o.merchant = f.merchant and f.id = :flyersId
I am using hibernate to connect to my database for a project.
I would like to have a query that gets the products out of my database with the discription and name in a certain language. The parameter I have is the short name for the language, so first I would have to get the id of the language and then get the text in the required languages.
I have tried the following hql query, without success.
from Products as p
where p.productlanguages.languages.shortname like 'eng'
This is an image of the part of the database where the data should come from:
I have got the desired result with an sql query, but I can't seem to get it to work in hibernate. But I would prefer to do this in hql.
SELECT * FROM products p
INNER JOIN productlanguage pl ON pl.Products_id = p.id
WHERE pl.Languages_id =
(
SELECT id FROM languages
WHERE Shortname = 'eng'
);
Could anyone tell me how to build this hql query?
Thank you.
Try below:
from Products p INNER JOIN p.productlanguages pl
where pl.languages.shortname ='eng'
I am assuming that you have mapped Product-Productlanguages relationship as OneToMany and Productlanguages-Langages relationship as ManyToOne as depicted in your E-R diagram.
EDIT: There seems to be a typo in Productlanguage mapping at line public Languages getLanguages() {barcode, remove the barcode in the end.
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="Languages_id", nullable=false, insertable=false, updatable=false)
public Languages getLanguages() {barcode
return this.languages;
}
I have a situation that I need to apply another Condition inside ON clause while using Hibernate Criteria.
I am writing my MySQL and I am unable to find any reasonable way of converting it in Hibernate Criteria.
SELECT s.StudentID AS StudentID, sc.CourseID AS CourseID
FROM Student s
LEFT JOIN StudentCourse sc ON
(sc.StudentID = s.StudentID AND sc.CourseID = 'XXX')
What I am doing in this Query
I want all the student List either enrolled in specified course or not.
IF I have four Students the and only one student is enrolled in a course the result should be like
StudentID, CourseID
1 NULL
2 XXX
3 NULL
4 NULL
So far I what I have done is
Criteria cr = getSession().createCriteria(Student.class);
cr.createAlias("studentCourse", "sc", CriteriaSpecification.LEFT_JOIN)
.add(Restrictions.eq("sc.CourseID", 'XXX'));
By running this statement I get the query equivalent to the following query
SELECT *
FROM Student s
LEFT JOIN StudentCourse sc ON (sc.StudentID = s.StudentID)
WHERE sc.CourseID = 'XXX'
Now this query does not serve the purpose of the query. It returns only one row where CourseID is not null.
EDIT
Hibernate Version 3.4.0GA
You can move your second criteria into the general WHERE clause like
WHERE (sc.CourseID = 'XXX' or sc.CourseID is null)