SELECT query for multiple column with multiple table - java

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?

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

Why this hql statement is like an inner join?

Why this HQL statement is like an inner join?
select
user.id,
user.allocationVersion,
user.tx.statusId,
user.userId,
user.nameFirst,
user.nameLast,
user.email1,
user.statusId,
user.tx.name,
user.note1,
user.note2
from
module.bb.jpa.User as user
where user.clientId = :clientId
order by user.id DESC
The TX class which is referenced in the User class can be null. Why do I get a result as if I did an inner join? I just get Users with a TX but I want all of them.
The HQL reference talks about this in section 14.4:
HQL supports two forms of association joining: implicit and explicit.
The queries shown in the previous section all use the explicit form,
that is, where the join keyword is explicitly used in the from clause.
This is the recommended form.
The implicit form does not use the join keyword. Instead, the
associations are "dereferenced" using dot-notation. implicit joins can
appear in any of the HQL clauses. implicit join result in inner joins
in the resulting SQL statement.
from Cat as cat where cat.mate.name like '%s%'
[highlighting by me].
What your HQL is basically equivalent to is:
select
user.id,
user.allocationVersion,
user.tx.statusId,
user.userId,
user.nameFirst,
user.nameLast,
user.email1,
user.statusId,
user.tx.name,
user.note1,
user.note2
from
module.bb.jpa.User as user
join module.bb.jpa.Tx as tx -- This is an abbreviated inner join
where user.clientId = :clientId
order by user.id DESC
To "correct" this behaviour you will have to explicitly specify a left outer join or left join for short.
Because you have referenced tx.name in user. It should not work if you access it in Java but in HQL to get the value for this column Hibernate make implicit join. To get all values you should do it explicitly and include outer join option.

How to fetch many-to-many relationship entity

I have following table structure
TABLE1
T1_ID
T1_Col1
TABLE2
T1_ID
T3_ID
TABLE3
T3_ID
T3_COL1
Table1 and Table3 are joined by a middle table which is Table2. Now I have only T1_ID and I want to fetch all the rows from Table3 which are associated with T1_ID. A simple SQL query would be
select T1.*, T3.*
from TABLE1 T1, TABLE T2, TABLE3 T3
where T1.T1_ID = T2.T1_ID
and T2.T3_ID = T3.T3_ID
So how can i do this in hibernate/jpa ... I have yet to write my entity classes for Table1, Table2, Table3. I want to execute this query as part of Table1, so that i can write a method say entity.fetchAssociatedTable3(). The easiest approach i can think of is in fetchAssociatedTable3 i can put custom queries like the one i mentioned above. But since i am using hibernate/jpa I want to know if there is a better way to do this.
UPDATE
Apparently, my question isn't clear enough. I want to do something as user Dragan Bozanovic mentioned. However, What i want to know that
How would i write Table1 entity ? I mean what annotations i would put on the columns etc which will make hibernate/jpa understand that this column is related to Table3 column via Table2
I guess if question 1 is answered, then it would be difficult to write getEntity3s() method. But if (for a noob) there is something that I need to know, I would appreciate.
Assuming that you will have a many-to-many association between Entity1 (mapped to TABLE1) and Entity3 (mapped to TABLE3), you can either:
1) read the Entity1 by id and get all of the Entity3s from it:
Entity1 entity1 = entityManager.find(Entity1.class, entity1Id);
Collection<Entity3> entity3s = entity1.getEntity3s();
2) or, execute the JPQL query to get Entity3s without loading the Entity1 instance:
select distinct e3 from Entity3 e3 join Entity1 e1 where e1.id = :entity1Id
First thing you would need do is to stop thinking in terms of tables when using ORM tool (Hibernate/JPA). You model your classes and their relations and let the ORM tool help with the mappings declaratively. Your join table just is serving here for creating relation many to many relation between two entities. So in terms of classes you would have only Entity1 and Entity3. You would not be creating a class representing join table (unless of course you want it to have other attributes other than foreign keys in which case it would qualify to be a Entity class in it's own right). And then you can use either method suggested by #Dragan i.e., loading by primary key or using explicit HQL/JPQL.

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.

Inner Join with NamedQuery?

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.

Categories

Resources