无法使用Java / Hibernate在NativeQuery中反序列化DateTime

时间:2017-03-13 21:33:58

标签: java json jackson jodatime

简化示例

我在其中运行带有日期的本机查询:

SELECT id, start FROM event;

我做了一个SqlResultSetMapping,如:

@SqlResultSetMapping(
        name="EventMapping",
        classes={
                @ConstructorResult(
                        targetClass=de.teamsystems.domain.OverviewEvent.class,
                        columns={
                                @ColumnResult(name="id", type = Long.class ),    
                                @ColumnResult(name="start", type = DateTime.class )

                        }
                )
        }
)

我的OverviewEvent类看起来像:

@Entity
public class OverviewEvent  {

    @Id
    private Long id;

    private String name;


    private DateTime start;

    public Long getId() {
        return id;
    }

    public DateTime getStart() {
        return start;
    }

    public OverviewEvent(Long id, DateTime start) {
        this.id = id;
        this.start = start;
    }

}

当我在控制器中执行此代码时,出现以下异常:

{
    "error": "Internal Server Error",
    "exception": "javax.persistence.PersistenceException",
    "message": "org.hibernate.type.SerializationException: could not deserialize",
    "path": "/event",
    "status": 500,
    "timestamp": "2017-03-13T22:22:30.527+0100"
}

日志文件说:

2017-03-13 22:22:30.523 ERROR 23479 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.type.SerializationException: could not deserialize] with root cause

java.io.StreamCorruptedException: invalid stream header: 32303137
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:808) ~[na:1.8.0_111]

当我将DateTime更改为OverviewEvent类和SqlResultSetMapping中的String时,它可以正常工作。但我想使用日期时间格式。

有没有人能帮我解决这个例外。我尝试了不同的东西,例如:

@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private DateTime start;

但例外保持不变。谢谢你帮助我。

1 个答案:

答案 0 :(得分:1)

尝试使用Date (java.util.Date)代替DateTime

  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
  private Date start;

或为DateTime创建自定义de / serializer。