use datetime instead of datetime2 sqlserver hibernate

僤鯓⒐⒋嵵緔 提交于 2019-12-11 13:43:13

问题


I have hibernate configured as auto-update. I have a mssql-server 2012. Hibernate creates my java.util.Date objects as datetime2 in the database. Is there a possiblity to force hibernate to create datetime in the database?

I know that I can use annotations on the fields in my object, but there are too many. So I would like to configure hibernate, so that every java.util.Date becomes automatically datetime in the databse.


回答1:


The first thing coming to my mind is defining a new Hibernate Dialect, which maps the Java data types to datetime, instead of the default datetime2.

A complete class example:

public class ModifiedSQLServerDialect extends SQLServer2008Dialect {
    public ModifiedSQLServerDialect () {
        super();
        registerColumnType( Types.TIMESTAMP, "datetime" );
    }
}

If you look at the source of SQLServer2008Dialect (assuming Hibernate 4.3), you may see that the Types.TIMESTAMP is mapped to "datetime2", we are effectively redefining it, in our own ModifiedSQLServerDialect.

Using the new dialect

To use the new dialect, we have just defined, you need to add the following property to the persistence.xml file:

<property name="hibernate.dialect" value="com.example.ModifiedSQLServerDialect" /> 


来源:https://stackoverflow.com/questions/29163911/use-datetime-instead-of-datetime2-sqlserver-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!