How to seed rand() in Spring Boot JPA query - spring-boot

In a Spring Boot JPA query, when adding a seed to function 'rand' I'm getting "org.hibernate.QueryException: function takes no arguments: rand"
#Query("select mt from MyTable mt order by rand(4711)")
My database supports both rand functions, with and without parameter.
Is there a way to make that JPA query work?

Related

How to prevent adding default table alias in hibernate #Joinformula

In my application I am using the following #JoinFormula
#JoinFormula(value="(select s.\"Id\" from \"Student\" s where ash.\"Class_Id\" = id)" )
However, at runtime the generated query is:
(
select
s.cla0_."Id"
from
cla0_."Student" s
where
s.cla0_."Class_Id" = cla0_.id) as formula4_0_,
I need to prevent adding cla0_ table alias to the formula query. How could it be done in hibernate?
I am using it in spring boot, and postgres as database.

Spring boot #Query ignores #Table on view call

I have a spring boot 2 application that works great with entities that are mapped to a table that is in a MariaDB. I now do a view call and I have mapped that entity to the view using the #Table(name="ViewExpiredAccounts") annotation and now when the method is called the table name is ignored. I have a JpaRepository with this method:
#Query(value = "SELECT v FROM ViewExpiredAccounts v")
List<ViewExpiredAccount> expiredAccounts();
When I call this method I get an error:
Table 'view_expired_accounts' doesn't exist
The query SHOULD! translate the table name so that the eventual SQL query sent to MariaDB is: SELECT * from ViewExpiredAccount however it doesnt do that. Is this a bug in Spring??
did you reset the hibernate naming strategy?
if yes, the following property might help
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

Using JdbcCursorItemReader and IN clause in the SQL query

I am developing a spring batch application and using the chunk based processing.
For Reader i am using the org.springframework.batch.item.database.JdbcCursorItemReader class.
When configuring the Reader and specifying the SQL property, how can we use the combination of preparedStatementSetter to set values for an IN clause in the SQL?
My SQL:
select * from Employee where employeeId IN (,,,,,,).
How can I dynamically set the values for IN clause using preparedStatementSetter?

Custom query within JPA server-managed session

I'm trying to execute an unrelated query (other_table) within a JTA session (server-managed) in order to do some validations, before persisting the bean EJB into DB with JPA.
Here is what I want to do (aprox):
#PersistenceUnit(unitName="DynamicDatabase")
EntityManagerFactory emf;
#TransactionAttribute(TransactionAttributeType.REQUIRED)
private long nextEntryid() {
em = emf.createEntityManager();
Query query = em.createQuery("select t from OTHER_TABLE t");
// do some validation and checking
MyTable bean = new MyTable();
em.persist(bean);
}
However I keep getting a server error, it does not allow to interact with other database items that are not persisted:
org.apache.openjpa.persistence.ArgumentException:
An error occurred while parsing the query filter (query): The name "OTHER_TABLE" is not a recognized entity (...) Perhaps you meant MyTable, which is a close match.
<persistence-unit name="DynamicDatabase" transaction-type="JTA">
<jta-data-source>jdbc/DB2DynamicConnection</jta-data-source>
<class>jorge.java.dynamicdatabase.db.MyTable</class>
</properties>
</persistence-unit>
The question is: what is the proper way to query/alter another table within the same JPA DB connection and JTA transaction?
Pretty newby about this, please be patient with me. Been working on this very long.
Edit: I don't think it's related but FYI I'm using WebSphere Liberty Profile 8.5.5.4, JSDK 8u31, EclipseEE Luna 4.4.2 for Web Dev. Going to add it to tags.
The problem is that you have a #NamedQuery that references the entity OTHER_TABLE, and that does not exist or not marked as being an Entity (try in both Java class and persistence.xml).
If the OtherTable Java class is not an entity and if it MUST remain so, then you could use Constructors in JPQL-queries:
SELECT NEW com.domain.reports.MyReport(u.firstName, u.lastName, u.birthday) FROM User u
If you need to write plain SQL queries, then you could do it using native queries, as they are known in the JPA specification.
Based on Andrei's suggestion, the JPQL (Java Persistence Query Language) operates on objects, not on tables. This means that em.createQuery() can't be used for universal database interaction.
To execute any SQL statement generally speaking (inside the container-managed transaction JTA), it is necessary to get the DB connection from the entity manager (it will return the persistence context unit JPA).
// Get container's objects
em = emf.createEntityManager();
java.sql.Connection conn = em.unwrap(java.sql.Connection.class);
// Run the query
Statement sql = conn.createStatement();
ResultSet rs = sql.executeQuery("select * from OTHER_TABLE");
rs.next()
(...)
//Container-managed connection shouldn't be closed.
rs.close;
sql.close;
Notice that unwrap call works for JPA but not for Hibernate (other questions already exist on this point). Notice the different language used for the SQL statement select * from than a named query JPQL select t from. Exception handling must be also controlled as usual with a } finally { clause.
That way would allow to execute a complex custom statement within server-managed transaction without using JAVA entities and I can finally sleep.

How to use table functions in queries with Spring Data

When using Spring Data JPA with Hibernate, what are the options available to write queries that join with table functions.
For example, I'd like to generate queries as described below:
CASE 1: SELECT * FROM getfoo(1) AS t1;
CASE 2: SELECT * FROM getfoo(1) x INNER JOIN tbl1 y on x.id = y.id;
Edit
To elaborate more, I'm using Spring Data for all things CRUD (It works great). However, I need to write complicated queries that join tables with "table functions". Table functions(AKA Table-Valued User-Defined Functions) are database functions that return tabled-values which can be used in the JOIN clause in combination with tables. Postgresql and Sql Server support them.
In the Spring Data realm, which includes much more than JPA, what are the options to consider when writing such queries? Whats the best practice from your experience? user2658013 was kind enough to describe one such approach using the entityManager.reateNativeQuery method.
In my mind here are the options:
JPA
Use #NamedStoredProcedureQuery ( >=JPA 2.1)
Use entityManager.createNativeQuery or #NamedNativeQuery
Non-standard
Use Spring Data's #Query to declare finder queries directly on repository methods.
Use SimpleJdbcCall
Any others?
I believe you are asking about Postgres stored functions. Postgres stored functions are analogous to "Stored Procedures". So I think you are asking how would invoke a stored procedure using JPA? Am I close?
The following pseudo code is derived from details published here (see section on Stored Procures):
http://www.oracle.com/technetwork/articles/vasiliev-jpql-087123.html
EntityManager em = emf.createEntityManager();
SOMEVAL_TYPE result = (SOMEVAL_TYPE)em.createNativeQuery("SELECT getfoo(?1) FROM SOMEDB")
.setParameter(1, SOME_PARM)
.getSingleResult();
In general you can use JPQL with JPA instead of SQL.
Note! The above assumes you have already created the stored function in you Postgres database.
Hope that helps :)

Resources