I have an entity orderdetails, where a user can have many ordernames I want to get all the ordername by userid using jpa named query. I tried this
SELECT o.orderName FROM OrderDetails o WHERE o.userId=:userId;
Since the return type will be List in the resultset, I executed the query like this
getEntityManager().createNamedQuery("getOrderNamesByUserId",
orderDetail.class).setParameter("userId", userId);
This obviously is not working. How can I get that query working? One way is to iterate the List but I wonder whether there is another way around?
Well this is non-compiled code snippet, you could try the following approach.
#Override
public List<OrderDetails> findOrders(Long userId) {
TypedQuery<OrderDetails> query = entityManager.createNamedQuery(
"OrderDetails.getOrderNamesByUserId", OrderDetails.class);
query.setParameter("userId", userId);
List<OrderDetails> list = query.getResultList();
return list;
}
If you just need to select one column(ordername), use getResultList() method.
Query query = getEntityManager().createNamedQuery("getOrderNamesByUserId", OrderDetail.class);
query.setParameter("userId", userId);
List<String> orderNameList = query.getResultList();
Related
I am returning only a few columns from a table in DB:
List<MyClass> l = (List<MyClass>) session.createQuery("Select p.one, p.two FROM MyClass p WHERE p.id IN :id")
.setParameter("userId", id)
.list();
However, the query returns List of arrays, e.g
l.get(0) // [0] is object representing p.one in query, [1] p.two
Is there a hibernate some effective way how to map it to MyClass object? So the query would actually return list of MyClass objects where selected properties would have values, others would be set to null?
I have read about new MyClass(arg1,arg2) way in the query with construtor, however i have also read it is ineffective.
Thanks for help!
You can use try catch block and use query.getSingleResult() to return Object.
Query query = em.createNativeQuery("FROM TipoUsuario WHERE NAME = :name;", TipoUsuario.class)
.setParameter("name", name);
TipoUsuario tipoUsuario = null;
try
{
tipoUsuario = (TipoUsuario) query.getSingleResult();
}
catch ( Exception e )
{
return null;
}
createNativeQuery is just a sample. You can use createNamedQuery instead and put HQL in Entity with annotation #NamedQueries.
If you want to create MyClass you just need to use the fully-qualified name of the class in your query, e.g.
SELECT NEW my.pack.MyClass(p.one, p.two) FROM MyClass p WHERE p.id IN :id
I haven't heard of this being ineffective, and I can't image why it would be. It's just calling the constructor on the result instead of returning it as an array or object. Overall, it's probably a very good way of fetching, since you only select the fields that you need.
This and other options are also explained in more detail here.
In the django orm I can do something like the following:
people = Person.objects.filter(first_name='david')
for person in people:
print person.last_name
How would I do the equivalent in Java Hibernate's orm? So far, I've been able to do a single get, but not a filter clause:
Person p = session.get(Person.class, "david");
What would be the correct way to do this though?
you can use native SQL
session.beginTransaction();
Person p = getSingleResult(session.createNativeQuery("SELECT * FROM People where name = 'david'",Person.class));
session.getTransaction().commit();
and the function getSingleResult would be somthing like this :
public static <T> T getSingleResult(TypedQuery<T> query) {
query.setMaxResults(1);
List<T> list = query.getResultList();
if (list == null || list.isEmpty()) {
return null;
}
return list.get(0);
}
you can get a list like this :
List<Person> list = session
.createNativeQuery("SELECT * FROM People", Person.class)
.getResultList();
There are several approaches to do this so here goes:
Lazy way - possibly bad if you have a tons of data is to just load up
the whole list of persons, stream it and apply a filter to it to
filter out objects not matching the given first name.
Use a HQL query (Hibernate Query Language) to create a select query
https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/chapters/query/hql/HQL.html
Use Hibernate's Criteria API to achieve the above
https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/chapters/query/criteria/Criteria.html
Alternatively you can even use a native SQL query to do the above.
I use JPA 1.0:
Query query;
query = em.createNamedQuery("getThresholdParameters");
query.setParameter(1, Integer.parseInt(circleId));
List<Object[]> resultList = new ArrayList();
resultList = query.getResultList();
Here I get result as List<Object[]>, thus I have to type convert all the parameters of the row to their respective types which is cumbersome.
In JPA 2.0 there is TypedQuery which return an entity object of type one specifies.
But as I am using JPA 1 I can't use it.
How to get result as Entity object of type I want??
EDIT:
QUERY
#Entity
#Table(name="GMA_THRESHOLD_PARAMETERS")
#NamedQuery(
name = "getThresholdParameters",
query = "select gmaTh.minNumberOc, gmaTh.minDurationOc, gmaTh.maxNumberIc, gmaTh.maxDurationIc, gmaTh.maxNumberCellId,"
+ "gmaTh.distinctBnumberRatio, gmaTh.minPercentDistinctBnumber from GmaThresholdParameter gmaTh "
+ "where gmaTh.id.circleId=?1 AND gmaTh.id.tspId=?2 AND gmaTh.id.flag=?3 "
)
Your query selects many fields. Such a query always returns a list of Object arrays. If you want a list containing instances of your GmaThresholdParameter entity, then the query should be
select gmaTh from GmaThresholdParameter gmaTh
where gmaTh.id.circleId=?1 AND gmaTh.id.tspId=?2 AND gmaTh.id.flag=?3
The code to get the list of entities would then be
List<GmaThresholdParameter> resultList = query.getResultList();
You'll get a type safety warning from the compiler, that you can ignore.
I can't respond to this as a comment so I'll just go ahead and make it an answer.
List<Object[]> resultList = new ArrayList(); // CREATE an empty ArrayList object
resultList = query.getResultList(); // getResultList ALSO returns its own ArrayList object
And since you assign the list that getResultList() returns to the same variable as you used for your own empty ArrayList, your application loses any connection to your own empty ArrayList and Java will collect it as garbage. Essentially you created it for absolutely no purpose.
what JB Nizet posted is enough.
List<GmaThresholdParameter> resultList = query.getResultList();
I have done something similar since I was using JPA 1 at that time:
final Collection<YourType> typedResult = new ArrayList<YourType>
for(final Object result : query.getResultList())
{
typedResult.add((YourType) result);
}
return typedResult;
List<GmaThresholdParamerter> result= query.getResultList();
for( GmaThresholdParamerter res : result)
{
System.out.println("" +res.getMinNumberOc());
System.out.println("" +res.getMinDurationOc());
}
I got a Set<UserDTO> collection in a not Hibernate object, and I got a User domain entity in Hibernate.
UserDTO contains less information about user (only id and name)
How can I select full Hibernate User Set/List from the DTO object?
Like this?
Set<UserDTO> setDTO = .....
String hql = "FROM User WHERE id IN (:userDTO )";
Query query = entityManager.createQuery(hql);
query.setParameter("userDTO", setDTO);
return query.getResultList();
Thanks
Almost. But you'd have to extract the IDs in a separate collection first:
Set<Long> ids = new HashSet<Long>(setDTO.size());
for (UserDTO dto : setDTO) {
ids.add(dto.getId());
}
Then proceed with the query, and pass the ids set as param.
Don't forget that you need to use Query#setParameterList() instead of Query#setParameter.
This is in my DAO:
public List<Weather> getCurrentWeather() {
return sessionFactory.getCurrentSession().createQuery("from Weather").list();
}
This gets all of the elements from table Weather. But lets say I wanna do something like this(I want only one element from table Weather):
public Weather getCurrentWeather() {
return sessionFactory.getCurrentSession().createQuery("from Weather where id = 1").list(); // here should be something else than list()
}
I know there should not be list() in the end, but what must I write there, to get only one object?
If you have an id, you just use get:
public Weather getCurrentWeather() {
return sessionFactory.getCurrentSession().get(Weather.class, 1);
}
If you do need to do a query, yeah you'll have to grab the top of the result set, or you can use uniqueResult() on the query.
Is there something wrong with getting a list? :) Even if you know there is only 1 hibernate cannot assume that. Getting a list is safer anyway!
public Weather getCurrentWeather() {
List<Weather> list = sessionFactory.getCurrentSession().createQuery("from Weather where id = 1").list(); // here should be something else than list()
return (list.isEmpty() ? null : list.get(0));
}
You need to use the Criteria API as below:
List<LeaveManagement> leaveManagements = session.createCriteria(LeaveManagement.class)
.add( Restrictions.isNull("approvedTimeStamp") )
.uniqueResult();
If you want to write a hql query you can write as:
String hql = "from LeaveManagement where approvedTimeStamp is null";
Query query = session.createQuery(hql);
LeaveManagement results = (LeaveManagement) query.uniqueResult();