Named native query mapping in orm.xml - spring-boot

I am very new to Hibernate. I am trying to externalize basic SQL query to orm.xml
My query
SELECT CURRENT_TIMESTAMP FROM DUAL
I have tried following :
<named-native-query
name="JobTrackerEntity.getCurrentTimestamp"
result-class="java.sql.Timestamp">
<query>
SELECT CURRENT_TIMESTAMP FROM DUAL
</query>
</named-native-query>
But I get following error:
org.hibernate.MappingException: Unknown entity: java.sql.Timestamp
Please let me know how can I write the query in orm.xml. Also if I can refer any resources to get better understanding.
Update:
I have added a method in repository interface as follows:
#Repository
public interface TrackerRepository extends JpaRepository<TrackerEntity, TrackerId> {
#Query(nativeQuery=true)
Timestamp getCurrentTimestamp();
}
I'm calling getCurrentTimestamp() to execute query.

You must remove result-class="java.sql.Timestamp" because the result-class property must be an Entity.
edit:
CURRENT_TIMESTAMP results in a missing mapping in Hibernate dialect. You must provide your own dialect or if you don't need the timezone you better use:
SELECT LOCALTIMESTAMP FROM DUAL

Related

How can I write a custom query with spring in mongo?

I'm trying to make a query and fetch data over mongodb with Spring. But I don't know mongo and spring very well. I have these fields in my table. How can I write a custom query with this query in SQL? I mean give the qp value of the record whose id is this. How can I write this please help..
SELECT qp
FROM tableName
WHERE id = request.getId();
my custom query method is it true?
public Object findQueryParams(ProcessInfo processInfo ){
Query query = Query.query(Criteria.where("id").is(processInfo .getId()).is(processInfo .getQueryParams()));
return query;
}

Schema-validation: missing table when upgrading to spring-boot-3 (Hibernate 6 )

Background:
I have upgraded my spring boot project from '2.5.12' to '3.0.0'.
As part of the upgrade hibernate was also updated to 6.1.5.
All the java entities are now using jakarta.persistence instead of javax.persistence
as required
The issue:
When the application starts an error is thrown
Schema-validation: missing table ...
The error is thrown from org.hibernate.tool.schema.internal.AbstractSchemaValidator
The function validateTable meant to validate that the entities match the DB tables.
#Override
protected void validateTables(
Metadata metadata,
DatabaseInformation databaseInformation,
ExecutionOptions options,
ContributableMatcher contributableInclusionFilter,
Dialect dialect, Namespace namespace) {
final NameSpaceTablesInformation tables = databaseInformation.getTablesInformation( namespace );
for ( Table table : namespace.getTables() ) {
if ( options.getSchemaFilter().includeTable( table )
&& table.isPhysicalTable()
&& contributableInclusionFilter.matches( table ) ) {
validateTable(
table,
tables.getTableInformation( table ),
metadata,
options,
dialect
);
}
}
}
Additional info:
The DB tables exist, i can log in and see them.
The databaseInformation.getTablesInformation( namespace ); returns empty results.
The namespace.getTables() shows all the tables correctly.
Hibernate generated classes are created O.K as part of the build (so annotations seem to be working).
Using MySQLDialect
Entities didn't change beside using jakarta.persistence
I don't get any "Connection refused " so connection to the DB is created.
The question:
Any idea what might be the cause?
Is there an issue with the model or reading schema data from the DB?
Might this be an issue of some dependency incompatibility?

Spring Data JPA - how to filter returned data based on a fields values?

I am trying to figure out how do I filter what data is being returned to me in Spring JPA.
I know that with Spring JDBC, I get full controll and I can basically write a query like:
SELECT * FROM CAR
WHERE ACCIDENT_DATE IS NULL
OR BUY_DATE >= CURRENT_DATE
ORDER BY CAR_NUMBER
But, with Spring JPA, we dont write queries, instead we write entities like
#Entity
#Table(name = "CAR", schema = "MY_SCHEMA")
public class Car {
#Id
public Long carNumber;
...
}
What is the way to filter which Cars are returned based on weather the
ACCIDENT_DATE is NULL and
BUY_DATE is greater than CURRENT_DATE
, ordered by CAR_NUMBER in Spring JPA?
With the help of #DirkDayne, figured out how to do this. Thank you Dirk
#Query("select c from CarEntity c where c.accidentDate is null or c.buyDate >= CURRENT_DATE")
List<CarEntity> getAllAvailableCars(Sort sort);
, then call it in service as:
List<CarEntity> cars= (List<CarEntity>) carRepository.getAllAvailableCars(Sort.by("carNumber"));

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);

Run two #NamedNativeQuery query on same entity Class

I want to define two #NamedNativequery on entity class . When tying to define eclipse gives a error.
Duplicate annotation of non-repeatable type #NamedNativeQuery. Only
annotation types marked #Repeatable can be used multiple times at one
target.
From that error , I know we cannot define two define two #NamedNativeQuery of the entity class like
#Entity
#Table(name = "abc")
#NamedNativeQuery(name = "ABC.getSomeMethod1" query = "some_query",resultSetMapping ="abcDTO")//1st name query
// #NamedNativeQuery(name = "some_name" query = "some_query",resultSetMapping ="some_dto")//try to define second query , but gives error
public class ABC {
}
I am using spring repository at dao layer to called the method which bind with this query
public interface SomeInterface extends JpaRepository<ABC, Long> {
#Query(nativeQuery =true)
List<ABCDTO> getSomeMethod1(#Param("someParam1") long someParam1, #Param("someParam2") String someParam2);
}
The senario is that I want to run the 1st native sql (which run fine) query and then run the 2nd native sql query(want to run this also from same). How to solve this or What is the possible solution.
If this way I cannot run the two native sql query then is there any other to achive this.
You can define multiple named queries like this
#NamedNativeQueries({
#NamedNativeQuery(name = "ABC.getSomeMethod1"
query = "some_query",resultSetMapping ="abcDTO"
),
#NamedNativeQuery(name = "some_name"
query = "some_query",resultSetMapping ="some_dto"
)
})
Then in the business layer under the transaction you can call these two queries one after another,
If its a simple join between two entities and select and display better go with join's. Always remember to have those columns index in the Table ;)

Resources