Reputation: 991
I have Entity "Task" that needs to have an internal component called "timestamps" that holds values for when the task was submitted, started and completed.
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer Id;
private String Status;
private Timestamps timestamps;
// getters setters
}
Then I created the Timestamps class
public class Timestamps {
private Timestamp submitted;
private Timestamp started;
private Timestamp completed;
//getter and setters
}
How do I make this mapping so when I retrieve the information in JSON format I have something like this?
# 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
}
}
Upvotes: 0
Views: 60
Reputation: 722
You can put the @Embeddable annotation on Timestamps. Hibernate will map the fields as columns in the same table. You might also need an @Embedded on the Timestamps field in Task (I cant remeber for certain if both sides need an annotation).
Upvotes: 1
Reputation: 4643
If you don't want to persist Timestamps
in DB and just use it In DTO This will helps you:
@Transient
annotation is used to indicate that a field is not to be persisted in the database.
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer Id;
private String Status;
@Transient
private Timestamps timestamps;
// getters setters
}
If you want to persist Timestamps
as a relation you should do something like this:
@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
}
Upvotes: 1