Envrionment: Java, Hibernate JPA provider, JPA, Oracle DB
I am trying to create a native query to fetch the data from the Oracle DB. One of the columns is a date column. The date is fetched, but the timestamp is coming out as 00:00:00. However, through an SQL browser, I can see the date and the time. How do I fetch the resultList along with the time?
org.hibernate.Query query = ((HibernateEntityManager) entityManager).getSession().
createSQLQuery(NATIVE_QUERY).setResultTransformer(org.hibernate.transform.Transformers.ALIAS_TO_ENTITY_MAP);
query.setString(0, accountNumber);;
query.setTimestamp(1, startDate).setTimestamp(2, endTime);
query.setTimestamp(3, startDate).setTimestamp(4,endTime);
List resultList = query.list();
The query itself (in the code above - NATIVE_QUERY) is a normal SQL query for - "Get me all user names and txn time within a given date range whether it is a new transaction or something that has changed in some form".
select u.first_name as firstName, u.last_name as lastName, tx.start_time as txnTime from user u, transaction tx where tx.user_id=u.user_id and tx.account_number=? and (tx.start_time > ? and tx.start_time < ? or tx.change_time > ? and tx.change_time < ?)
for(Object listItem : resultList){
Map map = (Map) listItem;
Date txnTime = (Date)map.get("txnTime".toUpperCase());
//--------> NOT FETCHING THE TIME. I get the time as 00:00:00
}
The domain model is very simple
#Entity
#Table(name="TRANSACTION")
#org.hibernate.annotations.Entity(
dynamicUpdate = true
)
public class Transaction{
#Id
#SequenceGenerator(name="txn_gen", sequenceName="TXN_S")
#GeneratedValue(generator="txn_gen")
#Column(name="TXN_ID")
private Long txnId;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="USER_ID", nullable=false)
private User user;
#Column(name="START_TIME", nullable=false)
#Temporal(TemporalType.TIMESTAMP)
private java.util.Date startTime;
#Column(name="CHANGE_TIME")
#Temporal(TemporalType.TIMESTAMP)
private java.util.Date changeTime;
}
#Entity
#Table(name="USER")
#org.hibernate.annotations.Entity(
dynamicUpdate = true
)
public class User {
#Id
#SequenceGenerator(name = "user_gen", sequenceName = "USER_S")
#GeneratedValue(generator = "user_gen")
#Column(name="USER_ID")
private Long userId;
#Column(length=500, name="FIRST_NAME")
private String firstName;
#Column(length=500, name="LAST_NAME")
private String lastName;
}
Related
Let's say I have an Entity class called Students
#Data
#Entity
#Table(name = "dbo.students")
public class Students implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private String studentId;
#Column(name = "name")
private String studentName;
#Column(name = "course")
private String studentCourse;
#Column(name = "date_admitted")
private String dateAdmitted;
}
And a MS SQL Table called students
++++++++++++++++++++++++++++++++++++++++++++++++++++
id name course date_admitted
1 Pankesh EEE 2020-10-21 07:52:30.977
2 Pankesh IT 2020-11-03 11:53:20.976
3 Pankesh CE 2020-09-11 08:30:29.975
++++++++++++++++++++++++++++++++++++++++++++++++++++
What I want to retrieve is the latest record
2 Pankesh IT 2020-11-03 11:53:20.976
My Hibernate Query
session.createQuery("FROM Students WHERE name='"+studentName+"' ORDER BY date_admitted DESC")
What Hibernate Query should I put for this case?
Note: I'm using AnnotationMapping method to map to MS SQL
Use entityManager.createQuery("FROM Students WHERE studentName = :name ORDER BY dateAdmitted DESC" ).setParameter("name", studentName).setMaxResults(1).getResultList();
I am new to Android Room Database.
I saw there have similar questions on that topic, but i really didn't understand what actually worked for this topic.
So, here I am trying to get the first date from the table, but while I query with that
#Query("select min(date) from user_items where userId = :userId ")
long getFirstDate(long userId);
I got the result as a minimum date is 01/01/1970
But i want the first date from the table to show the user.
My entity class User.java:
#Entity(tableName = "users")
public class User {
#PrimaryKey(autoGenerate = true)
private int id;
private String name;
private String email;
private String password;
private String securityAnswer;
// other staff here
}
My another entity has a relation with User table.
UserItem.java:
#Entity(tableName = "user_items", indices = {#Index("userId")}, foreignKeys = #ForeignKey(entity = User.class,
parentColumns = "id",
childColumns = "userId",
onDelete = CASCADE))
public class UserItems {
#PrimaryKey(autoGenerate = true)
private int id;
private String category;
private String amount;
private String date;
#ColumnInfo(name = "userId")
private int userId;
// setter and getter
}
My other all query worked fine except min(date) function.
This is my entity, i want the first date as i marked, to show the user
Finally I got the solution:
Here I change my query
Instead of this:
#Query("select min(date) from user_items where userId = :userId ")
long getFirstDate(long userId);
Use this:
#Query("select min(date) from user_items where userId = :userId ")
String getFirstDate(long userId);
Because if you look my UserItem.java class , here i am storing data as String
so, if i want to store String to the long type, it's not allowed.
Hope it will help you.
The query is returning the start of the UNIX epoch (01/01/1970) which indicates that you might have persisted (or attempted to persist) an invalid value in the date column for one of your rows. You might want to check for any suspicious values in the date column.
We have a deleted column on our table, is it possible to check that every time this table is queried the query has a condition for this column?
Some googling with better keywords (soft-delete) it seems I could do this with #When annotation. not exactly what I was looking but seems close enough.
You can check out #Where annotation.
org.hibernate.annotations.Where
Example:
If there's an Account Entity
#Entity(name = "Account")
#Where( clause = "active = true" )
public static class Account {
#Id
private Long id;
#ManyToOne
private Client client;
#Column(name = "account_type")
#Enumerated(EnumType.STRING)
private AccountType type;
private Double amount;
private Double rate;
private boolean active;
//Getters and setters omitted for brevity
}
and if the following code is used for fetching the accounts.
List<Account> accounts = entityManager.createQuery(
"select a from Account a", Account.class)
.getResultList();
then the following SQL will be generated
SELECT
a.id as id1_0_,
a.active as active2_0_,
a.amount as amount3_0_,
a.client_id as client_i6_0_,
a.rate as rate4_0_,
a.account_type as account_5_0_
FROM
Account a
WHERE ( a.active = true )
Hibernate ORM 5.2.18.Final User Guide
I have table employee as below,
id|name1|number
--|-----|------
01|test |100
02|test1|101
03|test2|102
I am using jpa with eclipselink implementation and database is postgresql.
Here my requirement is I want to get latest record using select query. Can anyone suggest the query to get latest record always.
Thanks,
You can use the below query for getting the appropriate result from mysql
select * from employee order by id desc limit 1
You must add updatedDate field in the entity class.
So I'll like to know if is there a SIMPLE way around my problem, meaning having #PrePersist or #PreUpdate or even other workaround to set the lastModified field still using session
Entity Class:
#Entity
#Table(name = "employee")
public class Employee {
#Id
#GeneratedValue
private Long id;
#Column(name = "name")
private String name;
#Column(name = "number")
private Long number;
#Column(name = "updated_at")
#Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
// getter setter
#PreUpdate
public void setChangeDate() {
this.updatedAt = new Date();
}
}
You can use JPA query. This exam:
String query = "SELECT emp FROM Employee emp order by updatedAt desc limit 1 ";
I have a SQL query like this:
SELECT h.name, h.created_date, tbl.*
FROM my_table tbl
LEFT JOIN
(SELECT name, max(created_date) created_date FROM my_table GROUP BY name) h
ON tbl.name = h.name;
It returns the row from my_table (which has multiple for name="") along with the maximum created_date for that name.
Is there a way to replicate this in a JPQL query?
Here is the gist of the Entity class, it's quite simple:
#Entity
#Table(name = "MY_TABLE")
#XmlRootElement
public class MyTable implements Serializable {
private BigDecimal tableId;
private String name;
private Date createdDate;
// ...
#Id
#Basic(optional = false)
#Column(name = "TABLE_ID")
#GeneratedValue(generator = "TBL_ID_SEQ")
public BigDecimal getTableId() {
return tableId;
}
#Basic(optional = false)
#Column(name = "NAME")
public String getName() {
return name;
}
#Basic(optional = false)
#Column(name = "CREATED_DATE", insertable = false)
#Temporal(TemporalType.TIMESTAMP)
public Date getCreatedDate() {
return createdDate;
}
// ... getters/setters
}
Just reading your question I guess you do not need another entity. Entities in JPA are the same like tables in SQL. Usually there is a 1:1 relationship between entities and tables. You just have to know how to invoke a query using JPQ. You need a entity manager, which invokes your statement.
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceUnit");
EntityManager em = emf.createEntityManager();
You have to define your persistence unit, i.e. in a pom file, or a config java file. So done you can go on coding something like this:
Query q = em.createQuery( "Your query in sql syntax as a string object" );
In respect to your entities and invoked query you will receive a List using
List<object> resultOfMyQuery = q.getResultList();
This is only one short example. But hopefully you got some buzzwords to look for ;)