Inner Join with NamedQuery? - java

I need to get data from three different tables and into a list. I was wondering how I do it with namedQuery? I've seen that it's possible by searching online but I just can't get it to work.
SELECT
Customer.name,
Customer.adress,
Orders.date,
Orders.order_id,
Product.product_name,
Product.price
FROM
Orders
INNER JOIN Customer ON Customer.customer_id=Orders.customer_id
INNER JOIN Product ON Product.product_id=Orders.product_id
ORDER BY
Orders.date
That's what I would want to convert to a namedQuery. It would be great if anyone could kick me in the right direction.

Seems I'm unfamiliar with the term named query.
But this is how you would do it in SQL
CREATE VIEW view_name AS
SELECT
Customer.name,
Customer.adress,
Orders.date,
Orders.order_id,
Product.product_name,
Product.price
FROM
Orders
INNER JOIN Customer ON Customer.customer_id=Orders.customer_id
INNER JOIN Product ON Product.product_id=Orders.product_id
ORDER BY
Orders.date
Then you can call it like so
SELECT * FROM view_name
Be warned though, views in views are terrible for performance.

Related

'ORDER BY' in JPQL-query adds 'CROSS JOIN' to produced sql thus reducing final results

I’m to create query with ordering by field of related entity, like this:
SELECT p FROM Patient p ORDER BY p.doctor.name
And sql-query that Hibernate builds based on that of JPQL uses CROSS JOIN with condition (effectively, inner join):
select patient0_.id as id1_1_, patient0_.doctor_id as doctor_i3_1_, patient0_.name as name2_1_
from patient patient0_ cross join doctor doctor1_
where patient0_.doctor_id=doctor1_.id
order by doctor1_.name
As a side-effect, all patients with nulls in ‘doctor’ field are excluded from result set. Is there any option I can switch to hint Hibernate to use LEFT JOIN in such cases? Can’t such a behavior be considered a bug? From common sense’ point, just adding ordering shoud not affect result count.
Example is intentionally simplified. In real world it’s a dynamically built criteria-query with variable set of filters and sortings. So I can not work it around and use explicit LEFT JOIN in JPQL.
I reproduced behavior of simplified example in version 5.3.9.Final and in latest 5.4.15.Final.
Appreciate any help.
You should use explicit join instead of hibernate implicit join.
SELECT p FROM Patient p left join fetch p.doctor d ORDER BY d.name
If there is lazy relation and it is not wanted that doctor is loaded, fetch should not be used.
SELECT p FROM Patient p left join p.doctor d ORDER BY d.name
This is how the implicit join is defined for JPA, as an inner join. So if you want to use left join semantics, you will have to use a an explicit left join.
If you want something more dynamic, I can recommend you take a look at a query builder like Blaze-Persistence that has left join semantics for implicit joins.
Here is a Spring WebMvc example application that supports dynamic filtering and sorting for paginated datatables: https://github.com/Blazebit/blaze-persistence/tree/master/examples/spring-data-webmvc

SELECT query for multiple column with multiple table

I attach one image of my problem:
In Testing jFrame jTextField I will insert customer id then after pressing ok button query will select and collect information related to that customer.Then it will show in the jTableModel.
I attach my database image.
Error is "SQL code cannot be executed".
You can do like this (without Join):
SELECT papers.paper_list,papers_rate.monday,papers_rate.tuesday,
papers_rate.wednesday,papers_rate.thrsday,papers_rate.friday,
papers_rate.saturday,papers_rate.sunday,magzines.magzine_name,magzines_rate.rate
FROM papers,papers_rate,magzines,magzines_rate
WHERE example_table.customer_id = ? AND other conditions"
This syntax is, in effect, a simple INNER JOIN. Some databases treat it exactly the same as an explicit JOIN. The WHERE clause tells the database which fields to correlate, and it returns results as if the tables listed were combined into a single table based on the provided conditions.(http://www.techrepublic.com/article/sql-basics-query-multiple-tables/)
You need to join the tables properly.
Like this:
SELECT
paper_list,monday,tuesday,wednesday,thrsday,friday,saturday,sunday,magzine_name,rate
FROM papers
LEFT JOIN papers_rate
ON papers_rate.paperId = papers.id
LEFT JOIN magzines
ON magzines.paperId = papers.id
LEFT JOIN magzines_rate
ON magzines_rate.magazineId = magzines.id
WHERE customer_id = ?"
If you do an inner join, all your results will vanish if you don't have a magazine_rate for example...
And check your spelling.
You're writing thrsday instead of thursday and magzine instead of magazine...
PS: And where does customer_id come from ?
Use joins to select multiple column from multiple tables. Refer this to get an understanding about the join and for join examples.
Note: There should be a common field between two tables to perform join operation
If the tables are related you must use JOIN: let's see an example (I don't know your tables fields, so I'll invent a custom example). Think about person and pet tables; the person tables could contain these fields:
Person (personID, first_name, last_name, age)
the pet table could contain these other fields:
Pet (petID, name, age, personID)
The personID field in the pet table identifies the owner of the pet. It is a simple 1:N relation. To select some values from these two tables you must do something like:
SELECT Person.first_name, Person.last_name, Pet.name
FROM Person INNER JOIN Pet ON
Person.personID = Pet.personID
WHERE Person.age > 30
This is just an example, clearly. And the INNER JOIN is just a join type (there are several join methods). Here you can find some documentation concerning these issues.
You need to either use a Join clause (... FROM papers JOIN papers_rate ON papers.[id_column] = papers_rate.[foreign_key]) or use an equi-join (replace JOIN...ON clause with a condition in the WHERE clause) (... FROM papers,papers_rate WHERE papers.[id] == papers_rate.[foreign_key])
Could you please post the schema of your tables?

Hibernate inheritance query

I have 4 entities:
User, Teacher, Student, Course
and 4 tables:
t_user, t_teacher_course, t_student_course, t_course
Teacher and Student extends User (with descriminators) and have #ManyToMany relationship with Course (User do NOT have)
Teacher's relations stored in t_teacher_course and Student's relations stored in t_student_course.
Now i want to select all users with courses (if they exists) in one query
select u from User u left join fetch u.courses c (notice that User do not have courses)
This select generated something like this:
select
...
from
T_USER user0_
left outer join
T_TEACHER_COURSE course1_
on user0_.USERID_=courses1_.TEACHER_
left outer join
T_COURSE course2_
on courses1_.LANE_=course2_.COURSENAME_
where
user0_.GROUP_=?
As you can see clearly Hibernate did NOT join with t_student_course table
I am using Hibernate 4.1Final
Question:
Does Hibernate support such queries
a) if supports then why it didn't fetched courses for Student entity?
b) if do not support than how can i select all users with their courses using JPQL?
Since u.courses could be student.courses or teacher.courses, Hibernate resolves the ambiguity by choosing the first (or last) association with this name in its metadata.
It might work if the name of the courses collection is not the same in both subclasses. For example, you could define Student.attendedCourses and Teacher.teachedCourses.
Otherwise, you'll have to issue two queries (one for teachers and one for students), and join the result lists. Or you'll have to pull up the association in the User entity.

Hibernate select with distinct - how does it work with an inner join?

First, I'm a total Hibernate novice.
Within hibernate, if you have an object, say author and author has a collection of books (say the list name is 'books'). If you run a Hibernate query, using using the following query I made up (not yet tested)
select distinct author from Author author inner join author.books as book
What exactly will the distinct do here?
The reason I ask is because I haven't selected a particular property in the select clause, such as
select distinct author.name ...
Also, what exactly will be unique about the objects which are returned?
First of all, if authors co-write books, you have a many-to-many association, and not a one-to-many.
That said, the query will return the list of all the authors who have written at least one book (that's the effect of the inner join). And each author will be exactly once in the returned list.

Hibernate: How to query to an object which it's collection proprty contains a specific value?

I've got a Player Object in which there is a Collection<Stock>. I'm willing to write a hibernate query which returns the list of players who have a specific stock (for example stock.symbol="**").
any ideas?
No problem use HQL with join syntax.
see it here
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/queryhql.html#queryhql-joins-forms
For example:
Player p join p.myStocks stock where stock.symbol = :symbol

Categories

Resources