问题
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