Spring 4 ZoneDateTime Restful recursive output - spring
I am new on Java 8 and Spring 4
i have tried to implement spring boot with module (Spring boot web, Spring boot jpa)
i have tried to implement JpaAuditing on my entity with the following code:
//AbstractAuditedEntity.class
#MappedSuperclass
public class AbstractAuditedEntity {
#CreatedBy
#Column(name = "CREATED_BY")
private String createdBy;
// #Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
#CreatedDate
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
#Column(name = "CREATED_DATE")
// #Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private ZonedDateTime createdDate;
#LastModifiedBy
#Column(name = "LAST_MODIFIED_BY")
private String lastModifiedBy;
// #Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
#LastModifiedDate
#Column(name = "LAST_MODIFIED_DATE")
// #Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private ZonedDateTime lastModifiedDate;
/*setter getter are omitted*/
}
and the User entity with the following code :
#Entity
#Table(name = "common_user")
public class User extends AbstractAuditedEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private Long id;
/*other fields are omitted*/
}
and my controller :
#RestController
public class UserCtrl {
#Autowired
UserRepository userRepository;
#RequestMapping(value = "/user", method = RequestMethod.GET)
#ResponseBody
public User index() {
User one = userRepository.findOne(1L);
return one;
}
}
the result is of field createdDate and lastModifiedDate are recursive :(
{"createdBy":"SYSTEM","createdDate":{"offset":{"totalSeconds":25200,"rules": {"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:00"},"zone":{"id":"Asia/Jakarta","rules":{"fixedOffset":false,"transitionRules":[],"transitions":[{"offsetBefore":{"totalSeconds":25632,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:07:12"},"offsetAfter":{"totalSeconds":26400,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:20"},"dateTimeAfter":{"hour":0,"minute":0,"nano":0,"second":0,"month":"JANUARY","year":1924,"dayOfMonth":1,"dayOfWeek":"TUESDAY","dayOfYear":1,"monthValue":1,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":768,"zero":false,"negative":false,"nano":0,"units":["SECONDS","NANOS"]},"gap":true,"overlap":false,"dateTimeBefore":{"hour":23,"minute":47,"nano":0,"second":12,"month":"DECEMBER","year":1923,"dayOfMonth":31,"dayOfWeek":"MONDAY","dayOfYear":365,"monthValue":12,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-1451719200,"nano":0}},{"offsetBefore":{"totalSeconds":26400,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:20"},"offsetAfter":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"dateTimeAfter":{"hour":0,"minute":10,"nano":0,"second":0,"month":"NOVEMBER","year":1932,"dayOfMonth":1,"dayOfWeek":"TUESDAY","dayOfYear":306,"monthValue":11,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":600,"zero":false,"negative":false,"nano":0,"units":["SECONDS","NANOS"]},"gap":true,"overlap":false,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"NOVEMBER","year":1932,"dayOfMonth":1,"dayOfWeek":"TUESDAY","dayOfYear":306,"monthValue":11,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-1172906400,"nano":0}},{"offsetBefore":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"offsetAfter":{"totalSeconds":32400,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+09:00"},"dateTimeAfter":{"hour":1,"minute":30,"nano":0,"second":0,"month":"MARCH","year":1942,"dayOfMonth":23,"dayOfWeek":"MONDAY","dayOfYear":82,"monthValue":3,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":5400,"zero":false,"negative":false,"nano":0,"units":["SECONDS","NANOS"]},"gap":true,"overlap":false,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"MARCH","year":1942,"dayOfMonth":23,"dayOfWeek":"MONDAY","dayOfYear":82,"monthValue":3,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-876641400,"nano":0}},{"offsetBefore":{"totalSeconds":32400,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+09:00"},"offsetAfter":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"dateTimeAfter":{"hour":22,"minute":30,"nano":0,"second":0,"month":"SEPTEMBER","year":1945,"dayOfMonth":22,"dayOfWeek":"SATURDAY","dayOfYear":265,"monthValue":9,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":-5400,"zero":false,"negative":true,"nano":0,"units":["SECONDS","NANOS"]},"gap":false,"overlap":true,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"SEPTEMBER","year":1945,"dayOfMonth":23,"dayOfWeek":"SUNDAY","dayOfYear":266,"monthValue":9,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-766054800,"nano":0}},{"offsetBefore":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"offsetAfter":{"totalSeconds":28800,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+08:00"},"dateTimeAfter":{"hour":0,"minute":30,"nano":0,"second":0,"month":"MAY","year":1948,"dayOfMonth":1,"dayOfWeek":"SATURDAY","dayOfYear":122,"monthValue":5,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":1800,"zero":false,"negative":false,"nano":0,"units":["SECONDS","NANOS"]},"gap":true,"overlap":false,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"MAY","year":1948,"dayOfMonth":1,"dayOfWeek":"SATURDAY","dayOfYear":122,"monthValue":5,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-683883000,"nano":0}},{"offsetBefore":{"totalSeconds":28800,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+08:00"},"offsetAfter":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"dateTimeAfter":{"hour":23,"minute":30,"nano":0,"second":0,"month":"APRIL","year":1950,"dayOfMonth":30,"dayOfWeek":"SUNDAY","dayOfYear":120,"monthValue":4,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":-1800,"zero":false,"negative":true,"nano":0,"units":["SECONDS","NANOS"]},"gap":false,"overlap":true,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"MAY","year":1950,"dayOfMonth":1,"dayOfWeek":"MONDAY","dayOfYear":121,"monthValue":5,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-620812800,"nano":0}},{"offsetBefore":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"offsetAfter":{"totalSeconds":25200,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:00"},"dateTimeAfter":{"hour":23,"minute":30,"nano":0,"second":0,"month":"DECEMBER","year":1963,"dayOfMonth":31,"dayOfWeek":"TUESDAY","dayOfYear":365,"monthValue":12,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":-1800,"zero":false,"negative":true,"nano":0,"units":["SECONDS","NANOS"]},"gap":false,"overlap":true,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"JANUARY","year":1964,"dayOfMonth":1,"dayOfWeek":"WEDNESDAY","dayOfYear":1,"monthValue":1,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-189415800,"nano":0}}]}},"hour":15,"minute":37,"nano":576000000,"second":41,"month":"AUGUST","year":2014,"dayOfMonth":21,"dayOfWeek":"THURSDAY","dayOfYear":233,"monthValue":8,"chronology":{"calendarType":"iso8601","id":"ISO"}},"lastModifiedBy":"SYSTEM","lastModifiedDate":{"offset":{"totalSeconds":25200,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:00"},"zone":{"id":"Asia/Jakarta","rules":{"fixedOffset":false,"transitionRules":[],"transitions":[{"offsetBefore":{"totalSeconds":25632,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:07:12"},"offsetAfter":{"totalSeconds":26400,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:20"},"dateTimeAfter":{"hour":0,"minute":0,"nano":0,"second":0,"month":"JANUARY","year":1924,"dayOfMonth":1,"dayOfWeek":"TUESDAY","dayOfYear":1,"monthValue":1,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":768,"zero":false,"negative":false,"nano":0,"units":["SECONDS","NANOS"]},"gap":true,"overlap":false,"dateTimeBefore":{"hour":23,"minute":47,"nano":0,"second":12,"month":"DECEMBER","year":1923,"dayOfMonth":31,"dayOfWeek":"MONDAY","dayOfYear":365,"monthValue":12,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-1451719200,"nano":0}},{"offsetBefore":{"totalSeconds":26400,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:20"},"offsetAfter":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"dateTimeAfter":{"hour":0,"minute":10,"nano":0,"second":0,"month":"NOVEMBER","year":1932,"dayOfMonth":1,"dayOfWeek":"TUESDAY","dayOfYear":306,"monthValue":11,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":600,"zero":false,"negative":false,"nano":0,"units":["SECONDS","NANOS"]},"gap":true,"overlap":false,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"NOVEMBER","year":1932,"dayOfMonth":1,"dayOfWeek":"TUESDAY","dayOfYear":306,"monthValue":11,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-1172906400,"nano":0}},{"offsetBefore":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"offsetAfter":{"totalSeconds":32400,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+09:00"},"dateTimeAfter":{"hour":1,"minute":30,"nano":0,"second":0,"month":"MARCH","year":1942,"dayOfMonth":23,"dayOfWeek":"MONDAY","dayOfYear":82,"monthValue":3,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":5400,"zero":false,"negative":false,"nano":0,"units":["SECONDS","NANOS"]},"gap":true,"overlap":false,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"MARCH","year":1942,"dayOfMonth":23,"dayOfWeek":"MONDAY","dayOfYear":82,"monthValue":3,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-876641400,"nano":0}},{"offsetBefore":{"totalSeconds":32400,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+09:00"},"offsetAfter":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"dateTimeAfter":{"hour":22,"minute":30,"nano":0,"second":0,"month":"SEPTEMBER","year":1945,"dayOfMonth":22,"dayOfWeek":"SATURDAY","dayOfYear":265,"monthValue":9,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":-5400,"zero":false,"negative":true,"nano":0,"units":["SECONDS","NANOS"]},"gap":false,"overlap":true,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"SEPTEMBER","year":1945,"dayOfMonth":23,"dayOfWeek":"SUNDAY","dayOfYear":266,"monthValue":9,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-766054800,"nano":0}},{"offsetBefore":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"offsetAfter":{"totalSeconds":28800,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+08:00"},"dateTimeAfter":{"hour":0,"minute":30,"nano":0,"second":0,"month":"MAY","year":1948,"dayOfMonth":1,"dayOfWeek":"SATURDAY","dayOfYear":122,"monthValue":5,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":1800,"zero":false,"negative":false,"nano":0,"units":["SECONDS","NANOS"]},"gap":true,"overlap":false,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"MAY","year":1948,"dayOfMonth":1,"dayOfWeek":"SATURDAY","dayOfYear":122,"monthValue":5,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-683883000,"nano":0}},{"offsetBefore":{"totalSeconds":28800,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+08:00"},"offsetAfter":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"dateTimeAfter":{"hour":23,"minute":30,"nano":0,"second":0,"month":"APRIL","year":1950,"dayOfMonth":30,"dayOfWeek":"SUNDAY","dayOfYear":120,"monthValue":4,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":-1800,"zero":false,"negative":true,"nano":0,"units":["SECONDS","NANOS"]},"gap":false,"overlap":true,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"MAY","year":1950,"dayOfMonth":1,"dayOfWeek":"MONDAY","dayOfYear":121,"monthValue":5,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-620812800,"nano":0}},{"offsetBefore":{"totalSeconds":27000,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:30"},"offsetAfter":{"totalSeconds":25200,"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"id":"+07:00"},"dateTimeAfter":{"hour":23,"minute":30,"nano":0,"second":0,"month":"DECEMBER","year":1963,"dayOfMonth":31,"dayOfWeek":"TUESDAY","dayOfYear":365,"monthValue":12,"chronology":{"calendarType":"iso8601","id":"ISO"}},"duration":{"seconds":-1800,"zero":false,"negative":true,"nano":0,"units":["SECONDS","NANOS"]},"gap":false,"overlap":true,"dateTimeBefore":{"hour":0,"minute":0,"nano":0,"second":0,"month":"JANUARY","year":1964,"dayOfMonth":1,"dayOfWeek":"WEDNESDAY","dayOfYear":1,"monthValue":1,"chronology":{"calendarType":"iso8601","id":"ISO"}},"instant":{"epochSecond":-189415800,"nano":0}}]}},"hour":15,"minute":37,"nano":576000000,"second":41,"month":"AUGUST","year":2014,"dayOfMonth":21,"dayOfWeek":"THURSDAY","dayOfYear":233,"monthValue":8,"chronology":{"calendarType":"iso8601","id":"ISO"}},"id":1,"firstName":"adil","lastName":"ramdan","username":"admin","password":null,"email":"adil.ramdan#gmail.com","photo":"pp.jpg","group":null,"shaPassword":null,"authToken":null}
How to format ZoneDateTime in the Restful ?thanks before
That's not actually recursive; you can see for yourself by posting that json string into http://jsonformatter.curiousconcept.com/.
If you want to use ZonedDateTime and you don't want all of its properties converted to JSON, you might add #JsonIgnore to the field and then adding getters for each field that you want. For example:
#JsonIgnore
#CreatedDate
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
#Column(name = "CREATED_DATE")
private ZonedDateTime createdDate;
public Month getMonthCreated(){
return createdDate.getMonth();
}
Related
#dbref cannot create a reference to an object with a null id
I'm working with spring boot and mongodb while trying to persist data with relation (OneToMany) I get this error: org.springframework.data.mapping.MappingException: Cannot create a reference to an object with a NULL id. My Enteties: public class ReleveBancaireEntity implements Serializable { #Id private ObjectId id; #CreatedDate #DateTimeFormat(iso = ISO.DATE_TIME) private Date dateReception; #DBRef private List<LigneReleveEntity> lignereleve = new ArrayList<>(); } public class LigneReleveEntity { #Id private ObjectId id; #CreatedDate #DateTimeFormat(iso = ISO.DATE_TIME) private Date dateOperation; #CreatedDate #DateTimeFormat(iso = ISO.DATE_TIME) private Date dateValue; private ObjectId releveBancaireId; } Saving data to MongoDB: public void addReleveBancaire(ReleveBancaireDTO releveBancaire) { ReleveBancaireEntity releveBancaireEntity = mapper.map(releveBancaire,ReleveBancaireEntity.class); List<LigneReleveEntity> ligneReleveEntities = ObjectMapperUtils.mapAll(releveBancaire.getLignereleve(),LigneReleveEntity .class); ligneReleveEntities.forEach(ligneReleveEntity -> ligneReleveEntity.setReleveBancaireId(releveBancaireEntity.getId())); releveBancaireEntity.setLignereleve(ligneReleveEntities); releveBancaireRepository.save(releveBancaireEntity); ligneReleveRepository.saveAll(ligneReleveEntities); }
Ignore field for query in spring-r2dbc
I am using spring r2dbc and ReactiveCrudRepository in spring webflex applicaition. I have a field which I need to ignore for when select query is generated ( in Controller code is r2dbcEntityTemplate.select(Tenant.class) ). I try to using #Transient ,But It doesn't work, still error: "Required property daysRemaining not found for class Tenant" With my limited experience with r2dbc, Thanks in advance. #Accessors(chain = true) #Table(value = "tenant") #Data #Builder public class Tenant { #Id private Long id; #Column(value = "organization_name") private String organizationName; #Version #Column private Long version; #Column private Boolean trialTenant; #DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") #JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") #Column private LocalDateTime tenantExpiredTime; #Transient //Dynamically calculate the remaining time private Long daysRemaining; public Long getDaysRemaining() { return Optional.ofNullable(tenantExpiredTime) .map(localDateTime -> Duration.between(localDateTime, LocalDateTime.now())) .map(Duration::toDays) .orElseGet(() -> null); } }
#ReadOnlyProperty annotation works.
Auto populate created_date, last_modified_date, created_by and last_modified_by in entity : Hibernate with JPA
I am new to Hibernate and JPA. I have several entities, each of which contains following four columns: 1. created_by 2. last_modified_by 3. created_date 4. last_modified_date I would like these columns to get auto-populated while saving the associated entity. Two sample entities are as follows: Entity 1: #Entity #Table(name = "my_entity1") #Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class MyEntity1 implements Serializable { private static final long serialVersionUID = 1L; #Id #GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; #Column(name = "name") private String name; #Column(name = "created_by") private String createdBy; #Column(name = "last_modified_by") private String lastModifiedBy; #Column(name = "created_date") private Instant createdDate; #Column(name = "last_modified_date") private String lastModifiedDate; } Entity 2: #Entity #Table(name = "my_entity2") #Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class MyEntity2 implements Serializable { private static final long serialVersionUID = 1L; #Id #GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; #Column(name = "description") private String description; #Column(name = "created_by") private String createdBy; #Column(name = "last_modified_by") private String lastModifiedBy; #Column(name = "created_date") private Instant createdDate; #Column(name = "last_modified_date") private String lastModifiedDate; } In this context, I have gone through following posts: How to autogenerate created or modified timestamp field?, How can you make a created_at column generate the creation date-time automatically like an ID automatically gets created?. I am getting how to capture the dates fields but I cannot understand how to capture created_by and last_modified_by.
Auditing Author using AuditorAware and Spring Security... To tell JPA about currently logged in user we will need to provide an implementation of AuditorAware and override getCurrentAuditor() method. And inside getCurrentAuditor() we will need to fetch currently logged in user. Like this: public class AuditorAwareImpl implements AuditorAware<String> { #Override public String getCurrentAuditor() { return "TestUser"; // Can use Spring Security to return currently logged in user // return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername() } } Now enable jpa auditing by using #EnableJpaAuditing #Configuration #EnableJpaAuditing(auditorAwareRef = "auditorAware") public class JpaConfig { #Bean public AuditorAware<String> auditorAware() { return new AuditorAwareImpl(); } } Look at this to get more details....
Spring Data JPA: How to fetch all entities of a specific type along with each entity's associated entities?
I have a Post entity #Entity public class Post { #Id private UUID id; #NotNull private String title; #NotNull private String content; #NotNull private String identifier; #NotNull private String category; #NotNull #Column(name = "created_at") private Date createdAt; #NotNull #Column(name = "updated_at") private Date updatedAt; public Post (){ } public Post (String title, String content, String category){ this.title = title; this.content = content; this.category = category; } // rest of the getters and setters } And this is my Comment entity: #Entity public class Comment { #Id #GeneratedValue(strategy = GenerationType.IDENTITY) private UUID id; #NotNull private String name; #NotNull #GeneratedValue(strategy = GenerationType.IDENTITY) private Integer identifier; #NotNull private String email; #NotNull private String content; #NotNull #ManyToOne #JoinColumn(name = "post_id") private Post postId; #NotNull #Column(name = "created_at") private Date createdAt; public Comment() { } public Comment(String name, String email, String content){ this.name = name; this.email = email; this.content = content; } } And this is my post controller: #RestController #RequestMapping("/posts") public class PostController { private String getIdentifier(String str){ return String.join("-", str.split(" ")); } #Autowired private PostService postService; #RequestMapping(value = "", method = {GET, HEAD}) public List<Post> getAllPosts(){ return postService.getAllPosts(); } #RequestMapping(value = "", method = {POST, OPTIONS}) public Post addNewPost(#RequestBody Post post){ post.setId(UUID.randomUUID()); post.setIdentifier(this.getIdentifier(post.getTitle())); post.setCreatedAt(new Date()); post.setUpdatedAt(new Date()); return postService.savePost(post); } #RequestMapping(value = "/{id}", method = {GET, HEAD}) public Post getOnePost(#PathVariable UUID id){ return postService.getOne(id); } #RequestMapping(value = "/{id}", method = DELETE) public void deleteOnePost(#PathVariable UUID id){ postService.deleteOnePost(id); } } My question is how do I fetch all the comments for each individual post, whenever I fetch all the posts? Sorry, I come from a NoSQL background, so this is a bit daunting at first.
What you need to do is to create a bidirectional #OneToMany association from the Post to Comments: add a field in Post class #OneToMany( mappedBy = "postId", cascade = CascadeType.ALL ) private List<Comments> comments = new ArrayList<>(); From now on, when you get Post from the database, Comments will be fetched at the same time.
Spring JPA audting is not invoked
I have implemented spring data jpa auditing. Below is my configuration file #Configuration #ComponentScan(basePackages = "com.myapplication.test") #EnableWebMvc #EnableTransactionManagement #EnableJpaRepositories(basePackages = "com.myapplication.test.repository") #EnableJpaAuditing(auditorAwareRef = "auditorProvider", dateTimeProviderRef = "dateTimeProvider") #EnableSpringDataWebSupport public class ApplicationConfiguration { private static final Logger loggger = Logger.getLogger(ApplicationConfiguration.class); #Autowired private ConfigurationProperties configProps; #Bean("auditorProvider") public AuditorAware<Integer> auditorProvider() { return () -> { AuthenticationToken authentication = (AuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); return (authentication != null && authentication.isAuthenticated()) ? authentication.getUser().getUserId() : null; }; } #Bean public DateTimeProvider dateTimeProvider() { return () -> GregorianCalendar.from(ZonedDateTime.now()); } } Here is my entity super class #MappedSuperclass #EntityListeners(AuditingEntityListener.class) public abstract class BaseEntity { #JsonIgnore #Column(name = "created_by", updatable = false) private Integer createdBy; #JsonIgnore #CreationTimestamp #Temporal(TemporalType.TIMESTAMP) #Column(name = "created_on", updatable = false) private Date createdOn; #JsonIgnore #Column(name = "last_updated_by") private Integer updatedBy; #JsonIgnore #UpdateTimestamp #Temporal(TemporalType.TIMESTAMP) #Column(name = "last_updated_on") private Date updatedOn; } auditorProvider is getting the user id from the Spring Security context. I have used spring-security-oauth2. below the versions of the libraries I am having <spring.version>4.3.6.RELEASE</spring.version> <hibernate.version>5.2.9.Final</hibernate.version> <springsecurity.version>4.1.4.RELEASE</springsecurity.version> <springsecurityoauth2.version>2.0.12.RELEASE</springsecurityoauth2.version> When I save an entity the auditing methods are not getting called(in debug) and created/updated fields are not updated in the table.
Instead of using the hibernate annotations, you should use the spring data ones like: #Column(name = "created_date", nullable = false, updatable = false) #CreatedDate private long createdDate; #Column(name = "modified_date") #LastModifiedDate private long modifiedDate; This always worked for me, as specified in this tutorial: Jpa Auditing