Hibernate find object from database by few params - spring

Can't find right query with few params.
Here is my query from DAO class:
public Notebook findByName(String name, Integer UserId) {
return (Notebook) sessionFactory.getCurrentSession().createQuery("from Notebook where ....");
}
I would like to get by this query object of Notebook by few params: name and user id(foreign key).
And i would like to get only one object, not list of objects even he has only 1 element.

The method createQuery(queryString) returns a Query on which you can set the parameters e.g.
Query query = createQuery("from Notebook where id=:id and title=:title");
query.setParameter("id", id);
query.setParameter("title", title);
query.setMaxResults(1);
query.uniqueResult(); // fetch the object.
If the query returns more then one results be sure to set setMaxResults() or an exception will be thrown.

First
Edit to
public Notebook findByName(String name, Integer UserId) {
return (Notebook) ....createQuery("from Notebook where ....")...uniqueResult;
}
BTW: I am not including the part where you are setting the parameters for your query
If there is no a unique result, uniqueResult throws an exception.
Be sure your query statement is very specific and you are including something like master.pk=child.fk (where pk should fk)
could you update and include the complete query statement?

Related

Spring Open Projection - Object and Additional Value

Let's assume we have a model like this:
class User {
String name;
Integer age;
}
The query returns results, and the extraField is mapped, but the user isn't.
I have a query that joins the User table with another table and returns the User object and one more field that comes from this other table.
Is it possible to define an open projection in Spring that would map the return values from the query? I guess it should look something like the following, but I can't get it to work.
interface UserProjection {
User getUser();
#Value("#{target.extrafield}")
String getExtraField();
}

SpringBoot named query: IN-clause not working for multiple values

"In clause" not working on passing multiple values
Repository code
#Query( "select myObject from MyObject myObject where myObject.anyColumn in :values" )
public List<MyObject> findPriDestByCntryAbbr(#Param("values") List<String> values);
Calling from service
List<String> values = Arrays.asList(valuesString.split(","));
List<MyObject> result = myObjectRepository.findByAnyColumns(values);
When i am passing single value it is retrieving correct information from table, But on passing multiple values in List "values" giving empty result
Ideally it should work. You should check the values variable.
The other way you can try is- without writing query.
As per the doc we can create MyObjectRepository interface by extending Repository interface and then have a method to fetch all MyObjects. It goes like:
public interface MyObjectRepository extends Repository<MyObject,**Long**> {
List<MyObject> findBy**AnyColumn**In(Collection<String> values);
}
"AnyColumn" is your column name and second parameter for Repository interface is as per your requirement.

How to Return all instances of the type with the given ID in JPA SpringBoot?

I'm trying to return (or fetch) all the records from the database based on an ID provided by me. I'm using JPA and i'm aware of findAll() method but it returns all the records without any criteria, I created a custom query and it is only returning a unique value from the table but i want to return all records based on a criteria.
For example, findAllByUserID(String UserID) method should return all the records based on that UserID not just one.
I'd appreciate any help or suggestion.
Thanks
Have a look at the doc. There you will find the keywords you can use to declare methods in repository interfaces that will generate the according queries:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
In your case: If userID is an attribute of your entity you can add a method
List<YourEntity> findByfindAllByUserID(String userId)
to your repository interface.
First, make sure that you're not using any aggregate function in your select query such as DISTINCT()
Then make sure that the the method which is implementing that query is returning a List of you're desired result.
here's how it should look :
#Query("select t from table t where t.code = ?1")
List<Result> findAllByUserID(String UserID);

A Jpa query annotation to return results as key value pairs

I have a users table and I am trying to use annotated Queries in spring boot to get a result set. I am able to get result set as a list, but that does not have field names. How do I get the result set with field name as key and value pairs?
Current response [[1,"Jay"]] , what I want to do is {"id":1,"Name":"Jay"}
-----Here is my repository class-----
#Repository
public interface UsersauthRepository2 extends JpaRepository<Users2,Long> {
#Query("select id,name,email from Users u where LOWER(email) = LOWER(:email) and LOWER(u.password) = LOWER(:password)")
List<Users2> querybyemail(#Param("email") String email,#Param("password") String password);
}
The request doesn't return fields names.
If you need to get them :
You have them already as method argument
You need to use reflection.
Good luck

Retrieving selected fields from database using Hibernate

I'm retrieving a list of rows with selected fields from Oracle database using Hibernate. The retrieval is made by the following method in one of the DAOs in my application.
#SuppressWarnings("unchecked")
public List<Object[]> getOldFileName(String []ids)
{
int len=ids.length;
Long longType[]=new Long[len];
for(int i=0;i<len;i++)
{
longType[i]=Long.valueOf(ids[i]);
}
return sessionFactory.getCurrentSession().createQuery("select catId, catImage from Category where catId in(:id)").setParameterList("id", longType).list();
}
Here I'm fetching two fields categoryId and categoryImage as listed in the given HQL query based on the catId supplied as an array of String[] as a method parameter via Spring. It works fine and there is no question about it.
But regarding my requirements, retrieving catId again is completely unnecessary and I would like to remove catId from the list of fields in the query something simply like the following.
select catImage from Category where catId in(:id)
If I try to execute this query then the following call to the preceding method inside the Spring controller class,
String temp[]=request.getParameter("setDel").split(",");
List<Object[]> oldFileNames = categoryService.getOldFileName(temp);
//Invokes the preceding method in DAO.
causes the following exception to be thrown,
java.lang.ClassCastException: java.lang.String cannot be cast to
[Ljava.lang.Object;
The exception message indicates that java.lang.String cannot be cast to an array of Objects - Object[]. It appears that the HQL statement attempts to get only a single value of type String instead of retrieving List<Object[]>.
I just want to delete files which are stored in a directory after retrieving their names from the database and mentioning of catId in the list of fields in HQL is completely unnecessary.
Why do I need to add catId in the list of fields of the HQL statement in this scenario?
The return type for the list should be List. When only one column comes back hibernate does not put the result into and Object[]

Resources