休眠映射内部类,错误“无法确定类型:timeStamps”

时间:2018-12-29 13:35:17

标签: java json hibernate jpa

我有一个实体“ Task”,它需要一个名为“ timestamps”的内部组件,该组件保存有关该任务的提交,启动和完成时间的值。

@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer Id;
    private String Status;
    private Timestamps timestamps;
    // getters setters
}

然后我创建了Timestamps类

public class Timestamps {
 private Timestamp submitted;
 private Timestamp started;
 private Timestamp completed;
 //getter and setters
}

如何进行此映射,以便在以JSON格式检索信息时出现类似这样的内容?

# task
{
    "task": # ASCII string
    "status": # one of "submitted", "started", "completed"
    "timestamps": {
    "submitted": # unix/epoch time
    "started": # unix/epoch time or null if not started
    "completed": # unix/epoch time or null if not completed
    }
}

2 个答案:

答案 0 :(得分:1)

如果您不想将Timestamps保留在数据库中而只在DTO中使用它,这将为您提供帮助:

@Transient批注用于指示字段不会保留在数据库中。

@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer Id;
private String Status;
@Transient
private Timestamps timestamps;
// getters setters
}

如果您想将Timestamps保留为一种关系,则应执行以下操作:

@Entity
public class Timestamps {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Integer Id;
 private Timestamp submitted;
 private Timestamp started;
 private Timestamp completed;
 //getter and setters
}

@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer Id;
private String Status;
@ManyToOne
private Timestamps timestamps;
// getters setters
}

答案 1 :(得分:1)

您可以将@Embeddable注释放在时间戳上。 Hibernate将字段映射为同一表中的列。 您可能还需要在Task中的“时间戳”字段上添加一个@Embedded(如果双方都需要注释,则我无法确定)。