How to add custom column name Spring Data JPA? [duplicate] - java

This question already has an answer here:
Column name as a parameter to Spring Data JPA Query
(1 answer)
Closed 6 years ago.
I have lots of column in my DB and don't want to write custom queries for all of them so consider the below method runs for every column name dynamicaly which i give as column_name. Is something like this possible or are there any other way to do that?
#Query("select #column_name from Item Where #column_name like %?2% ")
List<Item> getUniqueColumn(String column_name,String column_text);
By the way in spring documantation this case not mentioned.

You can only pass values that you are expecting as parameters to your HQL queries. You can't pass column or table names.
Hibernate is basically working here with a PreparedStatement, and a statement cannot be prepared where the table / columns being queried for are not known yet.
You would have to write some String replacement logic or build your query with the Criteria API
List<Object> getUniqueColumn(String column_name,String column_text){
StringBuilder query = new StringBuilder();
query.append("select #column_name ");
query.append("from Item ");
query.append("where #column_name like %?1%");
query = query.toString("#column_name", column_name);
session.createQuery(query).setString(1, column_text).list();
}
Also remember that what you are doing here is a projection and you will not get a List of Item but a List of Objects.

Related

How to add date in mysql database from Hibernate/Spring Jpa

I use spring boot, and I want to add 1 year to a specific column in mysql database
String queryRecherche = "UPDATE myTable t SET t.dateDebut = DATE_ADD(t.dateDebut, INTERVAL 1 YEAR) WHERE.id = 3 ";
Query query = em.createQuery(queryRecherche);;
query.executeUpdate();
But I get the folowing error :
org.hibernate.query.sqm.ParsingException: line 1:66 no viable alternative at input 'DATE_ADD(t.dateDebut,INTERVAL1'
Have you please any suggestions to do this.
You're using Hibernate 6 (I can tell by the error message), so the correct HQL syntax to use is:
UPDATE MyEntity t SET t.dateDebut = t.dateDebut + 1 year WHERE t.id = 3
You had three errors in your query:
You referred to the name of a table instead of the name of an entity class in the UPDATE clause.
You used the unportable MySQL DATE_ADD function instead of the portable HQL date/time arithmetic described here.
The syntax of your WHERE clause was garbled.
Perhaps you meant for this to be a native SQL query, in which case you called the wrong method of Session. But there's no need to use native SQL for the above query. As you can see, HQL is perfectly capable of expressing that query.
You can use SQL directly, via createNativeQuery, or register a new function as shown in this example to call it from HQL

Passing entire where clause to native spring jpa #Query [duplicate]

This question already has answers here:
Dynamic spring data jpa repository query with arbitrary AND clauses
(4 answers)
Closed 3 years ago.
Currently I'm unable to know the fields that will be within the SQL where clause (think adhoc) when creating the native SQL in my spring #Query. Therefore I'm passing in the entire where clause.
If I output the SQL to the console and paste it in to my sql editor I'm able to receive a valid resultset.
SELECT * FROM lorder WHERE order_id = 1196077
Last SQL output to the console was:
Hibernate:
/* dynamic native SQL query */ SELECT
*
FROM
lorder
WHERE
?
and the where clause value being passed in to the #query is:
order_id = 1196077
This is what I am currently doing which is not working.
#Query(
value = "SELECT * FROM lorder WHERE :where",
nativeQuery = true)
List<OrderEntity> listSelected(#Param("where") String where);
Not sure if passing the entire where clause is possible but I'm expecting a list. However I'm currently getting an empty collection.
Since using the #Query annotation you can only use named parameters (your :where) or ordinal parameters (e.g. ?1, ?2) of a specific Java-type, it's not possible to inject partial SQL-expressions.
However you could use a TypedQuery to add partial SQL to a query:
public List<OrderEntity> getOrdersUsingWhereClause(EntityManager em, String whereClause) {
TypedQuery<OrderEntity> query = em.createQuery(
"SELECT o FROM lorders o WHERE " + whereClause,
OrderEntity.class);
return query.getResultList();
}
See https://www.objectdb.com/java/jpa/query/parameter#Parameters_vs.Literals
The JPA's criteria query gives you more power to control where clause along with many other supported functionalities.
List of functions : https://en.wikibooks.org/wiki/Java_Persistence/Criteria
Criteria Queries : https://www.baeldung.com/hibernate-criteria-queries
Learn more about criteria query and criteria builder here

How to get latest 5 results from MySQL database using Spring,Hibernate

I need some help to fix my issue. I'm having a REST webservices project with Spring and Hibernate. By executing the POST call in POSTMAN,I've inserted some details into MySQL database. So, now i need to get latest 4(which means last 4) from the database table using GET
---id--------|----testname---|----testmethod----|---groupname---|-result----
So, these above mentioned are the columns of my database table. so i need to get last 4 results based on column groupname. So, i need to search by groupnameand id. The values of groupname will be like [Test]. So, can anyone tell is there any way to get those details through GET call.
If you want to retrieve some specific number of rows from database using hibernate then you can do something like this
Criteria cr = session.createCriteria(YourClass.class);
cr.setFirstResult(1);
cr.setMaxResults(4);
List results = cr.list();
The above code will retrieve first 4 rows from your DB.
If you want to retrieve last 4 rows then you have to somehow count the number of rows then use code like this
Criteria cr = session.createCriteria(YourClass.class);
cr.setFirstResult(count-4);
cr.setMaxResults(count);
List results = cr.list();
it will give you last 4 rows from your DB.
if you want to use HQL then you can do something like this
Query q = session.createQuery("FROM table");
q.setFirstResult(start);
q.setMaxResults(maxRows);

Force ebean to not include an ID in a generated query

I'm building a select that has to get me all distinct values from a table.
The sql I would normally write would look like this: "SELECT DISTINCT ARTIST FROM MUSICLIB"
However, ebean is generating the following: "SELECT DISTINCT ID, ARTIST FROM MUSICLIB"
The finder is as such:
find.select("artist").setDistinct(true).findList();
I've found that ebean is generating this ID on every single query, no matter what options I set.
How do I accomplish what I'm looking for?
You can't do that, Ebean for objects mapping requires ID field, and if you won't include it you'll get some mysterious exceptions.
Instead you can query DB without mapping and then write your SQL statement yourself:
SqlQuery sqlQuery = Ebean.createSqlQuery("SELECT DISTINCT artist FROM musiclib");
List<SqlRow> rows = sqlQuery.findList();
for (SqlRow row : rows) {
debug("I got one: " + row.getString("artist"));
}
Of course if artist is a relation, you need to perform additional query using list of found IDs with in(...) expression.

How do I access multiple fields in a JPA query?

I have a JPA query of the form:
SELECT category, count(*) AS c FROM ...
I know that if the query just returns a single column I can do something like:
List<Article> articles = query.getResultList();
However, how do I access the results when there are 2 or more columns as in the example above?
check out section 14.6 here: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-select
it will return a List of Object[] if you select more than one column, but dont get the actual entity.

Categories

Resources