sql query into hibernate - java

I am a beginner at hibernate and have read up a lot but I'm stuck at this one point.
In my JSF app that I'm implementing hibertate, I have this SQL query that works in my database:
SELECT *
FROM CourseProduct
INNER JOIN Course
ON CourseProduct.number=Course.number
inner join Product
on CourseProduct.product=Product.product;
I am trying to do the same thing with hibernate for my JSF application. So far I came up with:
List results = session.createCriteria(Course.class)
.setFetchMode("product", FetchMode.JOIN)
.setFetchMode("number", FetchMode.JOIN)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.list();
Is this correct or completely wrong? Also how do I access the fields from the results (if I even have to do that, since hibernate populates the classes for me)? It seems like the results I get are only the the Course Table, the value of the primary key in Product, but not the other 2 fields in the table Product.
EDIT
I guess I solved my own problem. It looks as though the above code is correct, I just didn't realize that in order to access the class Product I had to access it from the Set in the Course class! I just used an iterator to get the data I need in the get method for the set of Products in the Course class.

I guess I solved my own problem. It looks as though the above code is correct, I just didn't realize that in order to access the class Product I had to access it from the Set in the Course class! I just used an iterator to get the data I need in the get method for the set of Products in the Course class.
Update: I really solved the problem. I just got rid of hibernate. The sql query works fine, got my data using a perpared Statement and the result set using the regular old way (java.sql.DriverManager).
For some reason the hibernate driver didn't even like using my statement as a native SQL (kept giving me an exception trying to convert an Integer). I googled the problem and they say it's a bug in hibernate!

Related

is it possible to avoid array of arrays in JSON using sql query with join?

I'm not sure if it's even possible but I couldn't find any information about this (or didn't ask right question).
I write web app in Java/Spring and use my own queries (#Query annotation) in dao to get data from database. When I get data from one table everything is ok.
but when I join another table I get this:
.
My front-end guy, who gets data via JSON from me through url keep asking if I can change it so here is the question:
Is it possible to join table into one json array or it's just the way it is?
Sorry if it's a stupid question, probably I'm looking for something that doesn't even exist

How to bulk delete records using temporary tables in Hibernate?

I have a question. Where did these methods go?
Dialect.supportsTemporaryTables();
Dialect.generateTemporaryTableName();
Dialect.dropTemporaryTableAfterUse();
Dialect.getDropTemporaryTableString();
I've tried to browse git history for Dialect.java, but no luck. I found that something like
MultiTableBulkIdStrategy was created but I couldn't find any example of how to use it.
To the point...I have legacy code (using hibernate 4.3.11) which is doing batch delete from
multiple tables using temporary table. In those tables there may be 1000 rows, but also there may
be 10 milion rows. So just to make sure I don't kill DB with some crazy delete I create temp table where I put (using select query with some condition) 1000 ids at once
and then use this temp table to delete data from 4 tables. It's running in while cycle until all data based on some condition is not deleted.
Transaction is commited after each cycle.
To make it more complicated this code has to run on top of: mysql, mariadb, oracle, postgresql, sqlserver and h2.
It was done using native SQL, with methods mentioned above. But not I can't find a way how
to refactor it.
My first try was to create query using nested select like this:
delete from TABLE where id in (select id from TABLE where CONDITION limit 1000) but this is way slower as I have to run select query multiple times for each delete and limit is not supported in nested select in HQL.
Any ideas or pointers?
Thanks.
The methods were present in version 4.3.11 but removed in version 5.0.0. It seems a bit unusual that they were removed rather than deprecated - the background is on this Jira ticket.
To quote from this:
Long term, I think the best approach is to remove the Dialect method
intended to support table tabled in a piecemeal fashion and to make
MultiTableBulkIdStrategy be a fully self-contained contract.
The methods were removed in this commit.
So it seems that getDefaultMultiTableBulkIdStrategy() is the intended replacement for these methods - but I'm not entirely clear on how, as it currently has no Javadoc. Guess you could try to work it out from the source code ...or if all else fails, perhaps try to contact Steve Ebersole, who implemented the change?

DB connection in java--Query in JSP--Is it possible? And how

so here is my thought and problem at the same time...
I will create eventually a web app with Netbeans.
I have started by creating the database in POSTGRESQL which is ready and filled.
Anyway, to the point, of my first problem:
I have created a Java class, which manages to create a connection with the database. The method i am using, produces a Connection variable and returns it.
I don't want to make the query in there, BUT in the Jsp page. Is it possible? ALL the examples i have seen, are making the SQL Query in the Java page and not in the JSP page. But i don't want this, cause the queries i will make in the future of my project, will be like...thousands!
In general,i want the Db connection in the Java file and the Queries in jsp files.
What do you think?
thanks
Im pretty sure your question is violating the rules. Whatever.
Did you try NamedQueries? It's some time ago since I last wrote Java or JSP Code but as I understood your question, this should solve your problem.
Here a link
Explanation:
A named query is a statically defined query with a predefined
unchangeable query string. Using named queries instead of dynamic
queries may improve code organization by separating the JPQL query
strings from the Java code. It also enforces the use of query
parameters rather than embedding literals dynamically into the query
string and results in more efficient queries.
Example:
#Entity
#NamedQueries({
#NamedQuery(name="Country.findAll",
query="SELECT c FROM Country c"),
#NamedQuery(name="Country.findByName",
query="SELECT c FROM Country c WHERE c.name = :name"),
})
public class Country {
...
}

How to use Hibernate Query|Criteria.scroll() with DISTINCT without duplications

I have implemented usage of ScrollableResults for big DB table, everything worked perfectly until I wanted to do the same for another table using joins.
The entity where I have the problem has some one-to-many associations so I have to use DISTINCT not to get duplicates. Everything works well when I am obtaining results of the query using list(). But when I use scroll(), DISTINCT seems to be ignored completely - I just get many duplicates.
Query query = gameSession.createQuery("SELECT DISTINCT c FROM City c JOIN FETCH c.inhabitans i");
This works well, list has no duplicates:
List<City> list = query.list();
This is does not work (giving many duplicates like there would be no DISTINCT used):
ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);
Everything is the same when I use Criteria instead of Query. I have found out only 3 things about this particular problem:
Few questions like mine without answer,
A bug describing a case that could be absolutely the same like mine, but that should have been fixed long time ago,
Little comment in one of the SO answers telling that "DISTINCT_ROOT_ENTITY does not interact very well when scroll() is used".
This makes ScrollableResults useless for me, but I still need it because of the huge memory save. Do you know how to achieve scrolling results with DISTINCT used? Or any workaround?
Hibernate version: 4.2.4; JDK 7; DB: MSSQL
Add an "order by" clause to your query with the Id of the root entity.

Using Hibernate Criteria API To Query Many-To-One Relationships with Projections

I am trying to use Criteria API in following scenario:
I have two tables, Schedule and Route (with their classes and mappings).
Route has many-to-one relationship with Schedule.
Route has an integer property sequence.
Now I need to fetch all those Schedule objects whose associated Route objects fulfill the following condition:
route.sequence=no. of all Route objects associated with the given Schedule object
I have tried the following Criteria code for it:
Criteria crit = getSession().createCriteria(getPersistentClass())
.createCriteria("routes", "route")
.setProjection(Projections.projectionList()
.add( Projections.rowCount(), "routeCount"))
.add(Restrictions.not(Restrictions.ltProperty("route.sequence", "routeCount")));
But it generates the following sql:
select count(*) as y0_
from schedule this_
inner join route route1_ on this_.ID=route1_.scheduleId
where route1_.sequence<y0_
and throws the following error:
Unknown column 'y0_' in 'where clause'
Please help me if you have any suggestions.
The problem stems from an implementation issue with projections and restrictions. It seemed that there was a bug when trying to project and restrict on the same column - the generated sql was not valid. You will find that if run that sql directly against your database that it won't work.
The bug was originally logged here and it looked like it would not be fixed. But then I see another similar bug was logged here but I can't work out which release the fix will be available in.
The discussion that deals more with the issue and the theory behind it can be found here.
There is also another stackoverflow item dealing with the same question and offers a solution. I haven't tried to see if this approach works but it seemed to work for the people involved in the issue.

Categories

Resources