Find all entities with dates between, spring data jpa [duplicate] - spring

I'm trying to make a query to retrieve some data which has been created between two dates (represented as Instant).
Here below an extract from the Entity I'm using:
#Entity
public class HistoricalData {
#Id
#GeneratedValue
private Long id;
#Column
private String name;
#CreationTimestamp
private Instant timestamp;
#Column
private Double price;
}
And the query I've written to retrieve the data between the two Instants;
#Query("select h from HistoricalData h where h.timestamp between :timestampStart and :timestampEnd and upper(name) = upper(:name)")
List<HistoricalData> findHistoricalDataBetween(#NonNull Instant timestampStart, #NonNull Instant timestampEnd, #NonNull String name);
Which produces this SQL query:
select historical0_.id as id1_5_, historical0_.price as price2_5_, historical0_.timestamp as timestam3_5_ from historical_data historical0_ where (historical0_.timestamp between ? and ?) and upper(historical0_.name)=upper(?)
Also I wrote the "hibernate JPA" query just to try but no success:
List<HistoricalData> findHistoricalDataByTimestampAfterAndTimestampBeforeAndName(#NonNull Instant timestampStart, #NonNull Instant timestampEnd, #NonNull String name);
Keep in mind that all the above queries compile correctly and do not throw any exception, they just retrieve nothing from the database
The database I'm using is a latest version of MariaDB and the connector version is the 2.7.2
Also the SpringBoot version I'm using is the 2.5.3
Here is DDL from the table definition (automatically generated from Hibernate):
create table historical_data
(
id bigint not null primary key,
price double null,
timestamp datetime not null,
name varchar not null
);
An this is how the timestamp looks like in the database:
Even though records between those two Instants are present in the database I'm still getting nothing as a result from the query.

Looks like the reason is a time zone.
MySQL driver uses incorrect time zone transformations, using a default local time zone in place of a connection time zone (or vice versa).
Just debug this query inside MySQL driver to have fun and figure out what happens.
You can add parameters to the database URL to see which actual values are passed for the prepare statement
jdbc:mysql://<DATABASE_URL>?logger=com.mysql.cj.log.Slf4JLogger&profileSQL=true

Related

how to map custom sql query to model to load on jsp view in spring

I am beginner in spring. I want to show SQL data to JSP view page.
This is my SQL table
create table customer(
id int primary key,
name varchar(250),
salary int,
manager_id int
)
and I am trying to show data from this query
select m.id, m.name, m.salary, n.name from customer m, customer n where n.id=m.manager_id
So basically from this query, I am trying to show ID int, name varchar, salary int, manager_name varchar.
I have create the entity java class as below
#Entity
#Table(name="customer")
public class Customer{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private int id;
#Column
private String name;
#Column(name="manager_id")
private String manager;
#Column(name="salary")
private int salary;
............
............
}
This is the code of my DAO class
Session session= entityManager.unwrap(Session.class);
Query<Employee> query= session.createQuery(<above sql query need to add here?>,Customer.class);
return query.getResultList();
So the issues are,
This SQL query return the data which could not be matched to Customer Entity class. So do I need to create another Entity class for this? Is there any better way?
The above required SQL query is not able to execute. What the correct way to execute custom SQL query?
Regarding your first question: Yes there is better way. you can directly fetch the results in a projection dto class. take a at: https://vladmihalcea.com/the-best-way-to-map-a-projection-query-to-a-dto-with-jpa-and-hibernate/
About your second question: What Do you mean by saying the query does not execute?
Can you give us the Exception/Stacktrace? Did you try to execute the query (sql form of it) physically? Does it run then?

How to query more than one columns but not all columns with #Query but still use the Domain Data Model to map with Spring Data JDBC?

My Data model is
#Getter
#Setter
public class Customer {
#Id private ID id;
#CreatedDate protected Instant createdAt;
#LastModifiedDate protected Instant updatedAt;
#CreatedBy protected String createdBy;
#LastModifiedBy protected String updatedBy;
#Version protected Long version;
private UUID orderId;
private String offer;
}
My Repository is
public interface CustomerRepository extends CrudRepository<Customer, UUID> {
#Query(
"SELECT ID, Offer FROM Customer WHERE orderId = :orderId ")
List<Customer> findCustomerByOrderId(
#Param("orderId") UUID orderId);
}
This will result in an exception saying 'orderId column not found [42122-190]'. So Spring expects you to always query all the columns. I understand that with JPA we have a strong mapping between the Entities and the Data Schema. But the whole point of spring data JDBC is avoiding the tight coupling between POJO's data model and database schema. Why not the EntityRowMapper is just mapping NULL to the properties which are not part of the query?
Is there a way to tell the RowMapper used, to ignore properties which are not part of the query? Creating separate RowMapper for these simple queries seems a lot of unnecessary work.
I still can work around this by changing the query like
#Query(
"SELECT ID, Offer, OrderId, null as CreatedAt, null as CreatedBy, null as UpdatedAt, null as UpdatedBy, null as Version FROM Customer WHERE orderId = :orderId ")
But this will still serialize the entire object with null values. Am I missing something obvious here?
Note This is not Spring Data JPA. Its Spring Data JDBC.
Edit
Looking more into it, the exception is from h2 database lib.
Caused by: org.h2.jdbc.JdbcSQLException: Column "orderid" not found [42122-190]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.jdbc.JdbcResultSet.getColumnIndex(JdbcResultSet.java:3129)
at org.h2.jdbc.JdbcResultSet.get(JdbcResultSet.java:3217)
at org.h2.jdbc.JdbcResultSet.getObject(JdbcResultSet.java:522)
at com.zaxxer.hikari.pool.HikariProxyResultSet.getObject(HikariProxyResultSet.java)
at org.springframework.data.jdbc.core.EntityRowMapper.readFrom(EntityRowMapper.java:127)
You can't at least right now.
There are three solutions to this, two of which you already pointed out:
extend your select statement with , NULL as <column-name> for all the missing columns.
I'm not sure if
But this will still serialize the entire object with null values.
means that this isn't working for you in some way.
specify a RowMapper.
You could use a class containing exactly the fields returned by the query. It could even have getters for the other columns if you want an interface implemented by both your normal entity and the partial entity.
You write:
But the whole point of spring data JDBC is to avoid the tight coupling between pojo's data model and database schema.
This is not quite right.
An important goal of Spring Data JDBC is to not have a run time connection between entities and table rows.
This would require proxies or similar and brings a lot of complexity.
But the structural mapping between entities and table is probably going to be stronger (and certainly is right now) since all the variants of mappings available in JPA bring complexity.
And the main goal in Spring Data JDBC is to be conceptually simpler than JPA.
You also ask
Why not the EntityRowMapper is just mapping NULL to the properties which are not part of the query?
I'm not sure if I actively thought about it when I coded it but I don't like the idea of defaulting to NULL because this would make it easy to accidentally not load a column because you have a typo in an alias.
But I'm not against alternative solutions.
If you have an idea please create a feature request.

Mybatis, retrieve oracle field stored as CLOB spring boot

I have a user stored in oracle DB and one of the fields is stored as a CLOB(a simple Json {"profile": "man"}). I am using Mybatis and i try to retrieve the value.
So i am having:
<resultMap id=userResults>
<property="details" column="DETAILS" jdbcType="CLOB"
javaType="String"
typeHandler="org.apache.ibatis.type.ClobTypeHandler"
</resultMap>
and in the POJO:
the field details as a String with getter and setter.
class User{
private String name;
private String surname;
private String details;
//getters + setters
}
But nothing mapped in the end, even though the row exists in the DB.
The query is:
Select * FROM USER Where USER.id = #{id}
Any recommendations?
After some conversation on comments it turns out that the problem was the Oracle JDBC Driver after suggesting it and OP upgrading it He was able to make it work.

Javers: Diff DB entities with data from external source without ids

I'm getting data from an external source with no ids and then I store it in my DB. I'm using Spring with JPA (Hibernate). The ids are autogenerated on the first commit.
The changes in the external data is to be updated every night.
The first commit is trivial. I just create new entities for each new data object and save.
But further on I need to track the changes and just update the existing DB entities that have changed (and add and remove).
It doesn't matter which existing entity is to be updated.
How would I need to approach this using Javers? Is there an example?
Currently I'm thinking about something like:
Get existing entities from the DB.
Create new entities from the external data.
?
The new entities have no id. I would like to use Javers get the diff without needing any id. Diff the collections only based on the values.
Following a sample entity. None of the values apart the id is unique. Only the comparison of all other values can be used to check the identity to an existing entity.
#Entity
#Data
public class TiwHier {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#NotNull
private Long id;
#NotBlank
private String prodId;
private String pnGuid;
private String parentPnGuid;
private String typ;
private String name;
private String text;
private String klasse;
}

How to store Joda DateTime in MySQL

I've recently started using Joda time library for my test project.
Particularly i have been enjoying the capabilities of DateTime and functions for its manipulation.
My query is how do you store DateTime in MySql. I am using Spring & Hibernate for my application.
my current entity throws deserialisation errors whenever I try and use it:
#Entity
#Table(name = "test_storage")
public class TestEntity {
#Id #GeneratedValue
private int id;
#Column
private DateTime testDate;
//getters and setters
}
The mysql table structure is as follows:
Name: test_storage
Columns:
id INT NOT_NULL, AUTO_INCREMENT
testDate DATETIME
Any advice?
If you are using Hibernate 4+, then you can adopt the Jadira user types which allow you to map DateTime (and other JODA date time related class like LocalDate, LocalDateTime etc) to DB fields using different strategies.
Your mapping will look like
public class TestEntity {
//...
#Column
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime testDate;
}
Read the documents to know how to properly use these types to fit your requirements.
The biggest pitfall that you may face soon is, as Java's Date does not include timezone information nor does it sticks to UTC (JODA's user types still need to map to Timestamp/Date internally), you may want to make sure the way you store does provide proper information. For example, either store the date time as UTC, or store timezone information as a separate field, etc.
DATETIME would be my choice. See some more details at What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types and http://infopotato.com/blog/index/datetime_vs_timestamp

Resources