I've found one more solution that allows not to hardcode MySQL column definition snippet in your @Column
annotation. Define your own hibernate dialect by overriding org.hibernate.dialect.MySQLDialect
:
package org.yourproject;
import java.sql.Types;
import org.hibernate.dialect.MySQL5Dialect;
public class MySQL564PlusDialect extends MySQL5Dialect {
public MySQL564PlusDialect() {
super();
registerColumnType( Types.TIMESTAMP, 6, "datetime($l)" );
}
}
and specify it as hibernate property hibernate.dialect=org.yourproject.MySQL564PlusDialect
(the dialect you'll want to extend may vary, e.g. org.hibernate.dialect.MySQL5InnoDBDialect
instead).
Now you can adjust precision of your DATETIME
from within @Column
annotation by using length
attribute:
@Basic(optional=false)
@Column(name="moment", length=3)
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
public DateTime getMoment() {
...
which will produce DATETIME(3)
column definition meaning milliseconds precision. If you need the simple DATETIME
(no fractional seconds), just don't specify length. You can use value of length
up to 6 which would mean microseconds precision.
If you happen to use a dialect different from the above one (for example the standard org.hibernate.dialect.MySQLDialect
or maybe some other database), that will not break your code: the length
attribute on @Column
will be ignored.
P.S. It would be more sensible to exploit the precision
attribute of @Column
instead of length
, but simple replacing of "datetime($l)"
pattern with "datetime($p)"
one in my own dialect implementation does not work offhand.