王奕然
王奕然

Reputation: 4049

how to mapping Long to column datetime

my column type is datetime

`firstExpressTime` datetime NOT NULL ,

and my property is Long i use

@Column(nullable=false)
private Long firstExpressTime;

but when i save the entity,it report excpetion

Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '1415945797963' for column 'firstExpressTime' at row 1

how to solve it? thanks for your any help and suggestion at advance.

Upvotes: 0

Views: 113

Answers (2)

Oleg Kondrashov
Oleg Kondrashov

Reputation: 93

You should use AttributeConverter. Annotate your Long field like that:

@Convert(converter = DateToLongConverter.class)
    private Long birthdate;

and create your converter class:

@Converter
public class DateToLongConverter implements AttributeConverter<Long, Date> {
    @Override
    public Date convertToDatabaseColumn(Long attribute) {
        return new Date(attribute);
    }

    @Override
    public Long convertToEntityAttribute(Date dbData) {
        return dbData.getTime();
    }
}

Upvotes: 1

Matthias Steinbauer
Matthias Steinbauer

Reputation: 1776

Since on the database you use datetime you will need to use java.util.Date in your Java / Hibernate code.

However, I believe this should not be too much of a problem since you can get the underlying timestamp anytime by calling getTime()

DbHibernateObj obj = service.getMyObject(id);
long timestamp = obj.getFirstExpressTime().getTime();

Upvotes: 0

Related Questions