Hibernate将时间戳中的时间映射到时间00:00:00

时间:2014-03-19 01:28:19

标签: java mysql hibernate date time

考虑代码:

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;

import model.UserModel;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;


/**
 * This class adds initial values to the DB 
 * @author X2
 *
 */
public class InitialRecords {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;
    private static final String HIBERNATE_USERS = "usersModel.hbm.xml";

    /**
     * 
     * @param myDabatase
     * @throws ServletException
     */
    public void insertInitialRecords(ChatDatabase myDabatase) throws ServletException
    {
        Session session = null;
        java.util.Date date= new java.util.Date();
        Timestamp stamp = new Timestamp(date.getTime());    // get time & date
        Timestamp stamp2 = new Timestamp(date.getTime());   // get time & date
        UserModel user = new UserModel("jackson" , stamp , "Some cool message");
        UserModel user2 = new UserModel("yohan" , stamp2 , "Another cool message");

        // Setting up HIBERNATE
        // now use Hibernate to put it in the DB

        try
        {
            Configuration cfg = new Configuration().addResource(HIBERNATE_USERS).configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);

            // now insert the record of the person using Hibernate

            session = sessionFactory.openSession();
            System.out.println("Inserting Person records");
            Transaction tx = session.beginTransaction();

            // save the persons before hibernating

            session.save(user);
            session.save(user2);

            // execute
            tx.commit();
            System.out.println("Done");
            session.close();
            sessionFactory.close();

        }

        catch (Exception exp)
        {
            System.out.println("Error , here is the description :");
            System.out.println(exp.toString());
            System.exit(0); // abort the program
        }

    }

}

UserModel类:

package model;

import java.sql.Timestamp;

public class UserModel 
{

    static private int ctr;
    private int id;
    private String username;
    private Timestamp date;
    private String message;

    /**
     * Ctor
     * @param username
     * @param stamp
     * @param msg
     */
    public UserModel(String username , Timestamp stamp , String msg)
    {
        id = ctr + 1;
        ctr++;
        this.username = username;
        this.date = stamp;
        this.message = msg;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Timestamp getDate() {
        return date;
    }

    public void setDate(Timestamp date) {
        this.date = date;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }



}

当我映射记录user和user2时,Hibernate将记录映射到时间00:00:00

enter image description here

我该如何解决?

非常感谢

更新:

以下是我创建表格的方法:

public void createHibernateTableMessagesUsers() throws SQLException, Exception
{

    // this code assumes that the database "DATABASE_NAME" already exists
    // so the user must create that database before running the below code !!!
    try
    {
        Class.forName(FORNAME_URL);
        m_connectionHibernate = DriverManager.getConnection(URL , USERNAME , PASSWORD);
        m_statementHibernate = m_connectionHibernate.createStatement();

        m_statementHibernate.executeQuery("USE " + DATABASE_NAME);      // the name of the DATABASE
        m_statementHibernate.executeUpdate (
                "CREATE TABLE IF NOT EXISTS "+ MESSAGES_TABLE +" ("
                + "Username CHAR(40) ,  Message TEXT  , Date TIMESTAMP ,"
                        + " id INT AUTO_INCREMENT primary key NOT NULL" + ")");
    }

1 个答案:

答案 0 :(得分:2)

关注@Sotirios Delimanolis评论,以下是该问题的解决方案:

考虑以下UserModel类的hbm映射文件:

<?xml version='1.0'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!-- name of the package -->
<hibernate-mapping package="model">

<!-- name of the class & name of the table , that we want to translate the class-object to  -->
<class name="UserModel" table="messages_table">

<id name="id" type="int" column="Id" >
<generator class="identity"/>
</id>

<property name="username" column="Username" type="string"/>
<property name="date" column="Date" type="java.sql.Timestamp"/>
<property name="message" column="Message" type="string"/>

</class>
</hibernate-mapping>

date的财产中,我没有指定type="java.sql.Timestamp"!相反,我写了'type = Date&#39;。这就是造成这个问题的原因!