Distinct + Order By in Hibernate - java

Related to my last question
I have worked with that answer, but now I require to do with a bit modification using hibernate.
I need to now add a string to TestData class say String name
Then I want to fetch Collection of TestData from db using hibernate with the distinct name and sorting as I did in the CollectionSort class.
Can anyone help me how to do this using hibernate?
Thanks.

You can reuse that comparator in Hibernate, using #Sort annotation
Reference

Related

How to filter a Map Value using QueryDSL over Hibernate?

I have a Java entity Person that contains a
Map<AddressType, Address>,
and i need to filter to person that contains an address on specific city.
How can i do this with QueryDSL?
I verified that QueryDSL contains a method called "containsValue", but i don't know how i can use it. If i already have the exactly object that i need, i can simply put a
QPerson.person.addresses.containsValue(myAddress)
but this doesn't solve my problem :(
For example like this
query.from(person)
.innerJoin(person.addresses, address).on(address.city...)
.list(...)
Have a try:
JPAExpressions.selectFrom(address).where(address.city.eq("city"))

How to define a where clause in a onetomany class definition

I am new to Java Persistence etc
I have a one to many relation defined and it works, but I cannot define the where clause in the many entity.
For instance, my search is returning a list of orders and a collection of order items per order.
But, how do I apply a where clause in the LineItem entity class e.g.
The native SQL will look like this (roughly)
SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description
FROM Orders, LineItems WHERE Orders.OrderID = LineItems.OrderID
AND LineItems.Description IN ('XXX1', 'XXXXX2','XXXX3')`
AND LineItems.Quantity = 5
I dont know how to define the :
AND LineItems.Description IN ('XXX1', 'XXXXX2','XXXX3')
AND LineItems.Quantity = 5
in the LineItems class.
Please Help.
This is more of a workaround than an answer to your question, but it may be the only way to do it: Create a NamedQuery that restricts the results the way you want and use the NamedQuery instead. Here's a tutorial on how to do that.
The answers to this question imply that my suggestion is the only way to accomplish what you need. Those answers are Hibernate specific.

Hibernate update query

Any one tell me the HQL for this SQL code
UPDATE ModelClassname SET ClassVariablename=ClassVariablename+10 WHERE ClassVariableId=001;
There is no point using HQL to do that, you can use direct SQL if you want to do that, through a JDBC query (or even through a Hibernate query, you can use SQL queries).
Using HQL queries to update is only recommended when doing batch updates, not a single row.
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html#batch-direct
A more object-oriented way would be to load your object using HQL, do what you need to do in the Java world (columnValue +=10, whatever else you need to do), and then persist it back using hibernate session flush.
I suppose it involves more operations so it's less efficient (in pure performance) but depending on your Hibernate configuration (caching, clustering, second-level cache, etc.) it could be a lot better. Not to mention more testable, of course.
As others say, there is better ways, but if you really have to, then for example with following syntax:
update EntityName m set m.salary = m.salary +10 where m.id = 1
In addition to Adam Batkin's answer, I would like to add that such queries are generally not used (except if you need to modify a whole loat of rows at once) in Hibernate. The goal of Hibernate is to work with objects. So you generally do:
MyEntity m = (MyEntity) session.get(MyEntity.class, "001");
m.setValue(m.getValue() + 10);
// and the new value will automatically be written to database at flush time
The HQL query should look pretty similar, except instead of using table and column names, you should use the entity and property names (i.e. whatever you use in Java).
Please try this one
Query q = session.createQuery("from ModelClassname where ClassVariableId= :ClassVariableId");
q.setParameter("ClassVariableId", 001);
ModelClassname result = (ModelClassname)q.list().get(0);
Integer i = result.getClassVariableName();
result.setClassVariableName(i+10);
session.update(result);
With Regards,
Lavanyavathi.Bharathidhasan
HQL will help you here with bringing object to you with its session's help that you can update easily.
//id of employee that you want to update
int updatedEmployeeID = 6;
//exact employee that you want to update
Employee updateEmployee = session.get(Employee.class, updatedEmployeeID);
//for debug to see is that exact data that you want to update
System.out.println("Employee before update: "+updateEmployee);
//basically we use setter to update from the #Entity class
updateEmployee.setCompany("Arthur House");
//commit
session.getTransaction().commit();

Designing Java Object for SQL Query

Are there any good utils/frameworks which could generate Java Object for SQL Query?
QueryDsl automatically creates Query Objects from your Hibernate, JPA or JDO classes, but also from your DB schema.
Querying with Querydsl SQL is as
simple as this :
QCustomer customer = new QCustomer("c");
SQLTemplates dialect = new HSQLDBTemplates(); // SQL-dialect
SQLQuery query = new SQLQueryImpl(connection, dialect);
List<String> lastNames = query.from(customer)
.where(customer.firstName.eq("Bob"))
.list(customer.lastName);
It also supports subqueries:
To create a subquery you create a
SQLSubQuery instance, define the query
parameters via from, where etc and use
unique or list to create a subquery,
which is just a type-safe Querydsl
expression for the query. unique is
used for a unique (single) result and
list for a list result.
query.from(customer).where(
customer.status.eq(
new SQLSubQuery().from(customer2).unique(customer2.status.max()))
.list(customer.all())
Another example
query.from(customer).where(
customer.status.in(new SQLSubQuery().from(status).where(
status.level.lt(3)).list(status.id))
.list(customer.all())
I don't know its gonna be enough helpful but, as you asked for utils, I would suggest you to read about the QUERY OBJECT PATTERN (P of EAA, M. Fowler), if you have time to implement something, its a good beginning, otherwise you may lookfor any ORM framework.
I am using torque to do that. There is an example(Tutorial) which show what it can do at http://db.apache.org/torque/releases/torque-3.3/tutorial/step5.html
But what exactly is it you want? Do you just a simple way to serialize/unserialize objects to the database, and load them based on a primary/foreign key, or do you need to issue really complicated queries?

How to group selected data?

I have a comments tables from which I want to select and group comments by its foreign key profile_id.
I'm using jpa 2/hibernate and the tables have a one-to-many relationship from profile to comment.
Currently, the sql query retuns a list of comments and through the many-to-one relationship I get the profile for each comment.
I'd appreciate help in answering the following regarding post and pre query execution sorting:
How can I sort the returned list of comments, i.e. List<Comment>, by the profile_id (foreign key) of the comments table or the id (primary key) of the profile table?
How can/should I construct my sql query to sort the comments by profile?
Which of the two - pre or post sort - is a better practice?
Let the database do the sort for you : it's very efficient at doing it.
The HQL for this is very simple :
select c from Comment c order by c.profile.id
"sorting" (post sort) will be done by java in memory while "order by" (pre sort) will be done by the rdbms. Letting the rdbms do it with SQL is more efficient in most cases. The java sort will be controlled by the compareTo method of whatever object you are sorting
The SQL is as simple as adding an order by clause to your HQL like this:
from Comments order by profile_ID
or, using annotations, you can specify in the mapping how to order by:
#org.hibernate.annotations.OrderBy(
clause = "profile_id asc"
)
to have your results sorted in memory by java, you could map the collection of comments as a SortedMap or SortedSet
#org.hibernate.annotations.Sort(
type=org.hibernate.annotations.SortType.NATURAL
)
private SortedSet<Comment> comments = new TreeSet<Comment>();
The "NATURAL" in this case would expect Comment class to make sure the comments were sorted by profile_id by using the compareTo method.
you could also use SortType.CoMPARATOR for even more control if your Comments class implemented comparator.
referenced: Java Persistence with Hibernate
and http://henko.net/imperfection/sorted-collections-in-hibernate/

Categories

Resources