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.
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.
I look for short (one-method-long) solution of my problem.
I want to write query in spring data that does the same as:
select * from Users
where city = #EnteredData data OR homeTown = #EnteredData
I tried
List<User> findDistinctCity_findByHomeTown(String city);
I have no ideas how to find users whose city or homeTown is equal to given value in one method.
I will go with the below version. I better write my own queries instead of trying to use the Spring Data generated DSL one
#Query("select u from User u where u.city = :city or u.homeTown = :city") public List<User> getUserInfo(#Param("city") String city);
U can use method query, Add Or in query
List<User> findByCityOrHometowm(String name);
JpqL snippet will create as
where x.city= ?1 or x.hometown = ?2
I have using the Native Query in JPA Repository and my query is as:
select u.*, max(a.version_no) as versionNo from users u left join andother_table a on u.id=a.user_id where u.title='abc' group by id;
from my Query i get the "versionNo" which is not mapped to mu user modal.I have put this also in our user modal like as
#Transient
private String versionNo;
with is getter/setter.but in view i will get versionNo is null.
Please help me.
It is null because you annotated it as #Transient, so it is not populated with DB values. You can execute the query without mapping the results directly to your class, and populate the class manually (the query will return a list of Object[]). Other than this, I'm not aware of any alternatives (because of #Transient).
List<Object[]> results = session.createNativeQuery("select max(a.version_no) as versionNo, u.* from users u left join andother_table a on u.id=a.user_id where u.title='abc' group by id").list();
List<MyClass> myClasses = new ArrayList<MyClass>();
for (Object[] result : results) {
MyClass mc = new MyClass();
...
mc.setVersionNo(result[0]);
mc.setSomethingElse(result[1])
...
myClasses.add(mc);
}
Each entry in results list is an object array representing a row returned by native query. Columns are ordered as you select them, so if you put versionNo in the first place in SELECT clause, it will be available with result[0].
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();
I make this query:
String query = FROM Account acc WHERE acc.id = ? OR acc.id = ? or acc.id = ?...
I have array of ids:
long[] accountIds= {327913,327652,327910,330511,330643};
Then I make
getHibernateTemplate().find(query, accountIds);
I see that the list of accounts I get back from this query is:
327652,327910,327913,330511,330643, obviously , ordered by id.
Any chance I get it back in the order I wrote the ids?
Will appreciate all the help
You may want to use Criteria and its addOrder.
Something like this:
DetachedCriteria cr = DetachedCriteria.forClass(entityClass);
//Add expressions or restrictions to your citeria
//And add your ordering
cr.addOrder(Order.asc("yourID"));
List<T> ls = getHibernateTemplate().findByCriteria(cr);
return ls;
You can't do it on query level.
You can sort after loading from db, something like this
long[] accountIds= {327913,327652,327910,330511,330643};
List<Account> afterHql = getHibernateTemplate().find(query, accountIds);
List<Account> sortedList = new ArrayList<Acount>();
for (long id : accountIds)
{
for (Account account : afterHql)
{
if (account.getId() == id)
{
sortedList.add(account);
}
}
}
It is not possible to fetch results by providing any entity in OR Query or Restrictions.in(). As by deafult when you fire this kind of query it will search for the results id wise. So it will give you results id wise only. You can change the order by using Criteria either in asc or desc. And if you want to have results as per you enter id, then second answer is the only option.
You can only order by column values returned by the query, in a sequence defined by the data type . Wouldn't it be better to pre-order the IDs you supply, and order the query result by ID, so they come out in the same order?