Spring Data JPA separate createOn and updateOn - spring

my auditing works pretty nice but need to change create listener in that way to obtain null values in first update.
#MappedSuperclass
#Getter
#Setter
#ToString
#EntityListeners(AuditingEntityListener.class)
public abstract class AbstractEntity{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Version
private int version;
#CreatedBy
private String createdBy;
#LastModifiedBy
private String updatedBy;
#CreatedDate
private LocalDateTime createdAt;
#LastModifiedDate
private LocalDateTime updatedAt;
}
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#ToString
public class TestProfile extends AbstractEntity{
private String username;
}
Right now during create entity, the "updatedBy" and "updatedAt" is also fullfilled with duplicated values from "createdBy" and "createdAt". Should I change my default implementation to #PrePersist and #PreUpdate?
Here is my JpaConfig
#Configuration
#EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class AuditingConfig`enter code here` {
#Bean
public AuditorAware<String> auditorAware() {
return () -> Optional.of(((UserDetails) SecurityContextHolder
.getContext().getAuthentication().getPrincipal()).getUsername());
}
}

Related

Mongodb created date return null

When I create product createdDate return correct, but on update createdDate return null, I tried to implements persistable but still not working
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#SuperBuilder
public class BaseEntity implements Persistable<String> {
#MongoId(value = FieldType.OBJECT_ID)
private String id;
#CreatedDate
private Date createdDate;
#LastModifiedDate
private Date updatedDate;
#Override
public boolean isNew() {
return StringUtils.isEmpty(id);
}
}
To get value for createdDate you need to add #EnableMongoAuditing to main spring class
#SpringBootApplication
#EnableMongoAuditing

Spring data JPA: embedded ID error when saving the entity

I have the following entity classes:
#Embeddable
#Getter
#Setter
public class OrganizationCyclePlageKey implements Serializable {
#Column(name = "organization_id")
Long organizationId;
#Column(name = "cycle_plages_id")
Long cyclePlagesId;
...
equals() and hashCode() methods come here
#Entity
#Table(name = "organization_cycle_plages")
#Getter
#Setter
public class OrganizationCyclePlage {
#EmbeddedId
private OrganizationCyclePlageKey id;
#ManyToOne
#MapsId("organizationId")
#JoinColumn(name = "organization_id")
Organization organization;
#ManyToOne
#MapsId("cyclePlagesId")
#JoinColumn(name = "cycle_plages_id")
CyclePlage cyclePlage;
...
other attributes
}
#Entity
#Getter
#Setter
public class CyclePlage extends AbstractEntity {
#OneToMany(mappedBy = "cyclePlage")
private Set<OrganizationCyclePlage> organizationCyclePlages;
...
}
#Entity
#DynamicUpdate
#Getter
#Setter
public class Organization extends AbstractEntity {
#OneToMany(mappedBy = "organization")
private Set<OrganizationCyclePlage> organizationCyclePlages = new HashSet<>();
...
}
SpringBoot app starts up normally without errors.
But when I try to save an instance of OrganizationCyclePlage:
OrganizationCyclePlage ocp = new OrganizationCyclePlage();
ocp.setOrganization(organization);
ocp.setCyclePlage(cyclePlage);
organizationCyclePlageRepository.save(ocp);
it raises the error when calling organizationCyclePlageRepository.save(ocp):
org.hibernate.PropertyAccessException: Could not set field value [361] value by reflection : [class com.XXXX.OrganizationCyclePlageKey.cyclePlagesId] setter of com.XXXX.OrganizationCyclePlageKey.cyclePlagesId
What's wrong with these relations?
I had to add the constructor into the OrganizationCyclePlageKey class to init the foreign keys values as well a default constructor via #NoArgsConstructor annotation:
public OrganizationCyclePlageKey(Long organizationId, Long cyclePlagesId) {
this.organizationId = organizationId;
this.cyclePlagesId = cyclePlagesId;
}
and init the OrganizationCyclePlageKey instance in the OrganizationCyclePlage class:
public class OrganizationCyclePlage {
private OrganizationCyclePlageKey id = new OrganizationCyclePlageKey();
...
}

Embed complex object in entity

I want to embed the following
#Embeddable
public class BaseEntity implements Serializable {
#Id
#GeneratedValue
private UUID id;
#CreatedDate
#Column(name = "created_date", updatable = false)
private LocalDateTime createdDate;
}
into my room entity
#Entity
#Data
#NoArgsConstructor
#Table(name = "room")
public class room {
#EmbeddedId
private BaseEntity baseEntity;
#Column(length = 80, nullable = false)
private String name;
}
So that my generated table looks like this
room
id
createdDate
name
But id and createdDate are not getting embedded
Instead of #Embeddable just extend your BaseEntity
#MappedSuperclass
#Getter
#Setter
public class BaseEntity implements Serializable {
#Id
#GeneratedValue
private UUID id;
#CreatedDate
#Column(name = "created_date", updatable = false)
private LocalDateTime createdDate;
}
#Entity
#Data
#NoArgsConstructor
#Table(name = "room")
public class room extends BaseEntity{
#Column(length = 80, nullable = false)
private String name;
}

How to convert 2 DTO to 1 DTO mapstruct

How to convert TestDTO and QuestionDTO to PageTestDTO using mapstruct
I understand that this can be done quickly manually, but I would like to know this method
PageTestDTO
#NoArgsConstructor
#AllArgsConstructor
#Getter
#Setter
public class PageTestDTO {
private List<TestDTO> testDTOList;
private List<QuestionDTO> questionDTOList;
private Pageable pageable;
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public static class Pageable{
private Integer totalPages;
private Long totalElements;
private Integer number;
}
TestDTO
#NoArgsConstructor
#Getter
#Setter
public class TestDTO {
private Long id;
private String name;
private List<QuestionDTO> questionList;
public TestDTO(Long id, String name) {
this.id = id;
this.name = name;
}
QuestionDTO
#NoArgsConstructor
#Getter
#Setter
public class QuestionDTO {
private Long id;
private String question;
private List<AnswerDTO> answersList = new ArrayList<>();
public QuestionDTO(Long id, String question){
this.id = id;
this.question = question;
}

Why is my mapped DTO List null? What is the best way to map and persist Child Lists?

I have a simple problem - but I think "I am standing on the tube".
I have a spring boot rest api with JPA, Modelmapper, Entities and DTOs.
But the mapping doesn't work.
Entities:
#Getter
#Setter
#MappedSuperclass
public class AbstractEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
}
#Getter
#Setter
#Entity(name = "contacts")
public class Contact extends AbstractEntity {
#NotBlank
private String firstName;
#NotBlank
private String lastName;
#Valid
#OneToMany(mappedBy = "contact", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PhoneNumber> phoneNumberList;
}
#Getter
#Setter
#Entity(name = "phone_numbers")
public class PhoneNumber extends AbstractEntity {
#NotBlank
private String label;
#NotBlank
private String number;
#ManyToOne
#JoinColumn(name = "contact_id", referencedColumnName = "id")
#Setter(value = AccessLevel.NONE)
private Contact contact;
}
The DTOs:
#Getter
#Setter
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class ContactDTO {
private Long id;
private String firstName;
private String lastName;
List<PhoneNumberDTO> phoneNumberDTOList = new ArrayList<>();
}
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class PhoneNumberDTO {
private Long id;
private String label;
private String number;
}
My ModelMapperConfig:
#Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
.setFieldMatchingEnabled(true)
.setFieldAccessLevel(AccessLevel.PRIVATE);
return modelMapper;
}
Repo:
public interface ContactRepository extends JpaRepository<Contact, Long{
}
Service (only the create method):
#Override
public ContactDTO createOne(ContactDTO contactDTO) {
Contact contact = modelMapper.map(contactDTO, Contact.class);
contactRepository.save(contact);
return contactDTO;
}
Is this the correct way to persist the Contact with its multiple phonenumbers?
And how can I create a simple mapping?
If i want to persist it, there comes an error:
Column 'contact_id' cannot be null

Resources