0

I am trying to perform sanity check on db2 database, so I wrote:

Session session = _sessionFactory.openSession();

try{
    return session.createNativeQuery("SELECT CURRENT DATE from sysibm.sysdummy1", Date.class)
                            .stream().findFirst().orElse(null);
}
catch (Exception e){
    session.close();
    throw e;
}

Where Date is of type java.sql.Date.

I even tried to add this node to hibernate.cfg.xml file:

<mapping class="java.sql.Date"/>

Query itself works fine and returns "column" tagged as "1" with single row with date in yyyy-MM-dd format.
However when I execute the code I get error:

org.hibernate.MappingException: Unknown entity: java.sql.Date

Do I miss something?

  • 1
    I don't think we can use `java.sql.Date` as an entity for `ORM` purpose. This could help https://stackoverflow.com/questions/513317/how-do-i-use-the-current-date-in-an-hql-query-with-an-oracle-database – Arun Sudhakaran Feb 05 '20 at 11:20
  • @ArunSudhakaran I am java rookie, so I can be wrong, but .createNativeQuery() shuld get query as it is, instead of HQL. Furthermore I would expect it to be more a hibernate configuration problem. – Arkadiusz Raszeja Feb 05 '20 at 11:24
  • 1
    yeah that's what I said `java.sql.Date` is a class from `java.sql` package which you can't modify, so you can't give it as a mapping class. You should define a class with properties and those should be mapped to table columns in the configuration file. You can go though this tutorial https://www.tutorialspoint.com/hibernate/hibernate_configuration.htm – Arun Sudhakaran Feb 05 '20 at 11:34
  • @ArunSudhakaran Sorry if this question is too stupid, but do I really need to create POJO class just to get a single value from one column? – Arkadiusz Raszeja Feb 05 '20 at 11:39
  • @ArunSudhakaran I tried to create class named "Single Date" containing, gues what, single property named as date, mapped to column "DATE". Then I changed query to receive data "as DATE", added "model.mappings.SingleDate" to cfg.xml file and now I receive "Unknown entity: model.mappings.SingleDate" – Arkadiusz Raszeja Feb 05 '20 at 12:24
  • @ArunSudhakaran it works! Arun, your answers were super usefull! – Arkadiusz Raszeja Feb 05 '20 at 14:08

1 Answers1

0

ANSWER: The thing I have done is so ugly I wished it would not work but it does. I have created class:

@Entity
@Table
public class SingleDate {
    @Id
    private int id;
    private Date date;

    @Basic
    @Column(name = "DATE")
    public Date getDate() {
        return date;
    }
}

and perform:

    return session.createNativeQuery("SELECT 1 as ID, CURRENT DATE as DATE from sysibm.sysdummy1", SingleDate.class)
        .stream().findFirst().map(x -> x.getDate().toString()).orElse(null);