How to create sub resource with #RestRepositoryResource - spring

We are working on a Spring Boot API.
We use #RestRepositoryResource annotation to generate endpoints.
#RepositoryRestResource(collectionResourceRel = "datarow", path = "datarow")
public interface DataRowRepository extends MongoRepository<DataRow, String>
}
In the previous example, we create a endpoint /api/datarow.
But we want to change resource path like this : /api/dataset/{id}/datarow. Is it possible with #RestRepositoryResource ?
See our model :
public class Datarow {
#Getter #Setter
private String id;
#Getter #Setter
private String datasetId;
#Getter #Setter
private Address address;
}
public class Dataset {
#Getter #Setter
private String id;
#Getter #Setter
private String name;
#Getter #Setter
private String filePath;
#Getter #Setter
private Date uploadDate;
}
See our repository :
#RepositoryRestResource(collectionResourceRel = "datarow", path = "datarow")
public interface DatarowRepository extends MongoRepository<Datarow, String> {
}
Thanks !

Related

Spring Data JPA separate createOn and updateOn

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());
}
}

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();
...
}

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;
}

Embeddable is creating 2 tables jpa springs

I have below entites
AbstractOrderEntry :
#Getter #Setter
public class AbstractOrderEntry implements Serializable
{
#ElementCollection
private List<DiscountValue> discountValues = new ArrayList<>();}
}
CartEntry extending AbstractOrderEntry
#Entity
#EntityListeners(value = AuditListener.class)
#Table(name = "cartentry")
#Getter #Setter
public class CartEntry extends AbstractOrderEntry implements Serializable,Cloneable,Auditable
{
#Id
#Column(name="CartEntryID",nullable = false)
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
}
DiscountValueEntity:
#Embeddable
#Getter #Setter
public class DiscountValue {
private String code;
private BigDecimal value;
private BigDecimal appliedValue;
}
When I start the server it is generating to tables like
cart_discountValue
cart_discountvalue
one with camelcase and other is with lowercase.
We are also extending AbstractOrderEntry for order entity as well hence for order also 2 tables are getting created.
How can overcome this issue.Because of this issue table data is not properly persisting.
Thanks , Inadvance.
Sree

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