简体   繁体   中英

Insert with Hibernate native query does not work for java.util.Date

I am using Hibernate JPA and Spring with a Mysql database and I want to insert using a SQL statement like this:

Date saveDate = new Date();
java.sql.Timestamp timeStampDate = new Timestamp(saveDate.getTime());
Query persistableQuery = entityManager.createNativeQuery("INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, "
        + "TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES ("
        + true +", " + timeStampDate + ", " + description + ", " + title + ", "
        + needsLevelId + ", " + patientId + ", " + userId + " )");
persistableQuery.executeUpdate();

But after running it I get the following error:

WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: -11, SQLState: 37000
ERROR: org.hibernate.util.JDBCExceptionReporter - Unexpected token: 15 in statement
    [INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, TITLE,
    NEEDS_LEVEL_ID, PATIENT_ID, USER_ID)
    VALUES (true, 2011-03-01 15?, any description, , 193, 1, 3 )]

Could someone help me on this please?

PS. I am aware of using hibernate in non-native way, but I need to use native way. I am also of insert ...from... , but I don't think it will help.

Finally I think the problem is mainly with the date. How do you guys pass on MySQL a datetime type using Java?

Update:

The following works fine, I guess it is a java date to mysql datetime conversion problem.

("INSERT INTO TASK_ASSESSMENT "
     + "(ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, TITLE, "
     + "NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) "
     + "VALUES (true, 1999-12-22, '" + description + "', '" 
     + title + "', " + needsLevelId+", " + patientId 
     + ", " + userId + ")");

Could anyone please help me on how to convert java.util.Date to MySQL datetime ?

Don't use concatenation to insert data into queries, use parameters instead. It solves problem with wrong representation of values, as well as many other problems:

entityManager.createNativeQuery(
    "INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, "
    + "TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES (?, ?, ?, ?, ?, ?, ?)")
    .setParameter(1, true)
    .setParameter(2, saveDate, TemporalType.TIMESTAMP) // Since you want it to be a TIMESTAMP
    .setParameter(3, description)
    .setParameter(4, title)
    .setParameter(5, needsLevelId)
    .setParameter(6, patientId)
    .setParameter(7, userId) 
    .executeUpdate();

You can send parameter in method save, or what you use and use named SQL queries

 Query persistableQuery = entityManager.createNativeQuery("INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES (":active_flag",":timeStampDate", ":description", ":title", ":needsLevelId", ":patientId", ":userId" )").setParameter("active_flag", your_object.getactive_flag).setParametr and etc
persistableQuery.executeUpdate();
but somewhere create object with all this fields.

Looks like a few issues. Some of your fields should have quotes around them. Also, possibly you need to format the timestamp in a different way, not sure how mysql expects it?

Query persistableQuery = entityManager.createNativeQuery(
    "INSERT INTO TASK_ASSESSMENT 
        (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, "
    + "TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES ("
        + true +", " 
    + "'" + timeStampDate + "'"
    + ", " 
    + "'" + description + "'"
    + ", " 
    + "'" + title + "'"
    + ", "                                                            
    + "'" + needsLevelId + "')");

As far as formatting the date, I suspect you will need to look at the SimpleDateFormat class, which will let you get the date into whatever format mysql expects. See http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

In hibernate 5.3 and above positional parameters are deprecated so we need to use keys for parameter. Hql does not support insert with parameter. We need to follow below approch

import org.hibernate.query.Query;


    public void insertData() {

        String sql = "insert into employee(id,name,age,salary) values(:0,:1,:2,:3)";

        List<Object>  paramList = new ArrayList<Object>();
        paramList.add(1);    // id
        paramList.add("sumit"); // name
        paramList.add("23");  // age
        paramList.add(10000);  // salary

        Session session = null;
        try {
            session = getSessionfactory().openSession();

            Query query= session.createNativeQuery(sql);

            for(int i=0;i<paramList.size();i++) {
                query.setParameter(""+i,paramList.get(i));   // remember to add "" before i , we need to maintain key value pair in setParameter()
            }
            query.executeUpdate();
        }
        catch(Exception e) {
            System.out.println(e);
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM