Saturday, April 28, 2012

Calling getdate() using Hibernate

This post shows you how to use Hibernate to call Sybase's getdate() function in order to get the current date and time on your database server.

First, you need to create an entity to represent the date object. Hibernate will then map the result of getdate() to this entity.

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

 * Represents a date entity.
 * Used by hibernate to map the getdate() sybase function onto.
public class DBDateTime {

    private Date date;

     * @return the date
    public Date getDate() {
        return date;
The code snippet below shows how you would call getdate() on your Sybase database and get a Date returned:
Query query = entityManager.createNativeQuery("SELECT getdate() as date", 
DBDateTime dateEntity = (DBDateTime) query.getSingleResult();
Date now = dateEntity.getDate();

No comments:

Post a Comment