Monday, October 26, 2015

Manejo de fechas 1 en JPA

Cuando se esta trabajando con Fechas en JPA, si creamos un campo de tipo Date, jpa por defecto asumira que es un campo datetime y si no necesitamos las horas, minutos y segundos es un perdidad de tiempo almacenar este tipo de dato con esta caracteristica, para evitar este proceso cuando estemos en las entidades que vallamos a crear el campo fecha de tipo Date lo definimos asi

@Temporal(TemporalType.DATE)
private Date fecha;

de esta manera las fechas que creemos con
Date date = Calendar.getInstance().getTime();
seran solo "yyyy-MM-dd", ahora cuando realizasmo las consultas, no debemos de olvidar colocar siempre como parametro en la fecha que vamos a enviar el parametro TemporalType.DATE asi:

Query q = em.createQuery("select o from LoadFileHistory o where o.finishDate > :today ");
q.setParameter("today",todaysDateObject,TemporalType.DATE);
q.getResultList();
 
 
Ejemplo mas completo:
 
@Override
 public void getNumerosporusuario(String usuario) {
  
  Date date = Calendar.getInstance().getTime();
  List<NumerosAsignados> numeros;
  
  Query query = em.createQuery("Select numeros from NumerosAsignados numeros where numeros.usuarios.cedula=:id and numeros.fecha=:time");
  query.setParameter("id", usuario);
  query.setParameter("time", date,TemporalType.DATE);
  numeros = query.getResultList();
  
  
  
  System.out.println("we are here ..");
  for(NumerosAsignados str: numeros ){
   
   
   System.out.println("Getting.."+str.getNumero());
  }
  
  
  //return null;
 }
 
 
 
The annotation @Temporal in official javadoc is described like below:  
This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar.
So when the field variable is a java.util.Date or java.util.Calendar, it MUST be annotated by @Temporal.
There are 3 values for @Temporal
  • TemporalType.DATE
  • TemporalType.TIME
  • TemporalType.TIMESTAMP
Here is a demo to show the usage of there 3 values. The Entity 'MyEntity' has a field called 'lastUpdateTime' which is a defined as a java.util.Date variable. let's update it in java like this:
1
2
3
4
5
import java.util.Date;
//...
// MyEntity is the JPA entity, em is EntityManager context
MyEntity e = em.find(MyEntity.class, 1L); //get the row with id=1
e.setLastUpdateTime(new Date());

TemporalType.DATE


If the column annotated with @Temporal(TemporalType.DATE) like this:
1
2
3
@Temporal(TemporalType.DATE)
@Column(name="LAST_UPDATE_TIME")
private Date lastUpdateTime;

The record in database after update will look like:Snap_2014.12.22 12.49.51_001

TemporalType.TIME


If the column annotatedwith @Temporal(TemporalType.TIME) like this:
1
2
3
@Temporal(TemporalType.TIME)
@Column(name="LAST_UPDATE_TIME")
private Date lastUpdateTime;

The record in database after update will look like:Snap_2014.12.22 13.06.58_002

TemporalType.TIMESTAMP


If the column annotated with @Temporal(TemporalType.TIMESTAMP) like this:
1
2
3
@Temporal(TemporalType.TIMESTAMP)
@Column(name="LAST_UPDATE_TIME")
private Date lastUpdateTime;

The record in database after update will look like:Snap_2014.12.22 13.10.14_003
 

14 comments:

kevin Herrera said...

gracias por tu aporte, como se podria convertir el formato TIMESTAMP a date al momento de mostrarlo

Softgen Infotech said...

Wonderful thanks for sharing an amazing idea. keep it...

Upgrade your career Learn SAP MM Training in Bangalore from industry experts get Complete hands-on Training, Interview preparation, and Job Assistance at Softgen Infotech.

jeni said...

I like the helpful info you supply in your articles. I’ll bookmark your weblog and take a look at once more here regularly. I am relatively certain I will learn a lot of new stuff right here! Good luck for the following!
sap training in chennai

sap training in velachery

azure training in chennai

azure training in velachery

cyber security course in chennai

cyber security course in velachery

ethical hacking course in chennai

ethical hacking course in velachery

shiny said...

Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.



hardware and networking training in chennai

hardware and networking training in annanagar

xamarin training in chennai

xamarin training in annanagar

ios training in chennai

ios training in annanagar

iot training in chennai

iot training in annanagar

deiva said...

I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously in their life, he/she can earn his living by doing blogging.thank you for thizs article
web designing training in chennai

web designing training in omr

digital marketing training in chennai

digital marketing training in omr

rpa training in chennai

rpa training in omr

tally training in chennai

tally training in omr



praveen said...

Excellent post, From this post i got more detailed information,
Thanks to share with us,
oracle training in chennai

oracle training in porur

oracle dba training in chennai

oracle dba training in porur

ccna training in chennai

ccna training in porur

seo training in chennai

seo training in porur

Why Teeth Whitening is a Game-Changer: Visit the Best Dental Clinic in Madinaguda Today! said...

Informaticle post. Thanks for sharing with us. Madinaguda Dentist is a leading dental clinic in Madinaguda offering comprehensive dental care, including implants, braces, root canal treatment, and cosmetic dentistry. With experienced specialists and advanced technology, they ensure high-quality treatments for healthy and beautiful smiles. Perfect for families seeking reliable and professional dental services.
best dental clinic in madinaguda

Le Sweden said...

For those looking to achieve a flawless look for any occasion, professional beauty services can make all the difference. I highly recommend checking out the Beauty Clinic in Hyderabad. With exceptional expertise, personalised care, and advanced techniques, they ensure you look and feel your absolute best, enhancing your natural beauty and boosting your confidence.

Tech Leads IT said...

Java EE plays a vital role in building scalable enterprise applications. Similarly, Oracle Fusion HCM Online Training empowers learners to understand enterprise-level HR processes on the cloud, combining technical expertise with practical knowledge to manage real-world business needs effectively.
Oracle Fusion HCM Online Training

Visionnairex said...

The topic Manejo de fechas 1 en JPA is essential for understanding how to manage and format dates effectively within Java applications. Through the Future Leaders & Innovators Program, offered by VisionnaireX, learners can explore such technical concepts in depth while gaining real-world project experience. This program helps students enhance their programming and database management skills in a practical, future-focused way.
Future Leaders & Innovators Program

It4int Server said...

Working with dates in JPA can sometimes be tricky, especially with formatting and time zones. Having a reliable environment really helps when testing and running your code. IT4INT’s Colombia VPS provides that kind of stable and fast setup, so your projects can run smoothly without unexpected issues — a feature that makes development much easier!
colombia vps

ZetSIM said...

Very helpful explanation on handling dates in JPA! The examples make it easy to understand how it works in practice. Thanks for sharing such clear and useful content.
esim usa

unlimitmobile.com said...

Great post explaining how to handle dates in JPA with clear examples. The step‑by‑step code walkthrough makes it easier for Java developers to understand date handling and formatting in persistence contexts. Thanks for sharing such a practical and useful guide.
t mobile prepaid sim

snowflake masters team said...

Great explanation of date handling in JPA. The examples make it much easier to understand how temporal data is managed in entity mappings. Looking forward to reading the next part of this series.
Snowflake Training in Hyderabad

Post a Comment