Cannot execute query in GraphQL - spring

I'm trying to get into GraphQL and I followed a tutorial for a simple GraphQL + Spring + MySQL application, and I remade it for my own database. But when I try to execute my findAllDocuments query, I get this response in Postman:
"data": null,
"errors": [
{
"message": "Validation error of type FieldUndefined: Field 'findAllDocuments' in type 'query' is undefined # 'findAllDocuments'",
"locations": [
{
"line": 2,
"column": 5,
"sourceName": null
}
],
"description": "Field 'findAllDocuments' in type 'query' is undefined",
"validationErrorType": "FieldUndefined",
"queryPath": [
"findAllDocuments"
],
"errorType": "ValidationError",
"path": null,
"extensions": null
}
]
}
This is the entity I'm trying to get (it has some complex datatypes like Group or Media, that have similar implementation as Document class, I didn't include them to save space):
#Table(name = "documents")
public class Document {
#Id
#Column(name = "doc_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "title")
private String title;
#Column(name = "data")
private String data;
#Column(name = "data_asc")
private String dataAsc;
#Column(name = "external_link")
private String externalLink;
#OneToMany
#JoinColumn(name = "doc_id")
private List<DocumentForum> forums;
#Column(name = "navbar")
private String navbar;
#Column(name = "date_created")
private Date dateCreated;
#Column(name = "publish_start")
private Date publishStart;
#Column(name = "publish_end")
private Date publishEnd;
#OneToOne
#JoinColumn(name = "user_id")
private UserDetails author;
#OneToOne
#JoinColumn(name = "group_id")
private Group group;
#OneToMany(mappedBy = "document")
private List<Media> media;
#Column(name = "temp_id")
private Integer tempId;
#Column(name = "views_total")
private int viewsTotal;
#Column(name = "views_month")
private int viewsMonth;
#Column(name = "searchable")
private boolean searchable;
#Column(name = "available")
private boolean available;
#Column(name = "cacheable")
private boolean cacheable;
#Column(name = "file_name")
private String fileName;
#Column(name = "file_change")
private Date fileChange;
#Column(name = "sort_priority")
private int sortPriority;
#Column(name = "header_doc_id")
private int headerDocId;
#Column(name = "menu_doc_id")
private int menuDocId;
#Column(name = "footer_doc_id")
private int footerDocId;
#Column(name = "password_protected")
private String passwordProtected;
#Column(name = "html_head")
private String htmlHead;
#Column(name = "perex_place")
private String perexPlace;
#Column(name = "perex_image")
private String perexImage;
#Column(name = "perex_group")
private String perexGroup;
#Column(name = "show_in_menu")
private boolean showInMenu;
#Column(name = "event_date")
private Date eventDate;
#Column(name = "virtual_path")
private String virtualPath;
#Column(name = "sync_id")
private int syncId;
#Column(name = "sync_status")
private int syncStatus;
#Column(name = "logon_page_doc_id")
private int logonPageDocId;
#Column(name = "right_menu_doc_id")
private int rightMenuDocId;
#Column(name = "field_a")
private String fieldA;
#Column(name = "field_b")
private String fieldB;
#Column(name = "field_c")
private String fieldC;
#Column(name = "field_d")
private String fieldD;
#Column(name = "field_e")
private String fieldE;
#Column(name = "field_f")
private String fieldF;
#Column(name = "field_g")
private String fieldG;
#Column(name = "field_h")
private String fieldH;
#Column(name = "field_i")
private String fieldI;
#Column(name = "field_j")
private String fieldJ;
#Column(name = "field_k")
private String fieldK;
#Column(name = "field_l")
private String fieldL;
#Column(name = "disable_after_end")
private boolean disableAfterEnd;
#Column(name = "forum_count")
private int forumCount;
#Column(name = "field_m")
private String fieldM;
#Column(name = "field_n")
private String fieldN;
#Column(name = "field_o")
private String fieldO;
#Column(name = "field_p")
private String fieldP;
#Column(name = "field_q")
private String fieldQ;
#Column(name = "field_r")
private String fieldR;
#Column(name = "field_s")
private String fieldS;
#Column(name = "field_t")
private String fieldT;
#Column(name = "require_ssl")
private boolean requireSsl;
#Column(name = "root_group_l1")
private Integer rootGroupL1;
#Column(name = "root_group_l2")
private Integer rootGroupL2;
#Column(name = "root_group_l3")
private Integer rootGroupL3;
*********SETTER AND GETTERS*********
This is the .graphqls file for Document class:
scalar Date
type Document{
id: Int!
title: String!
data: String!
dataAsc: String!
externalLink: String!
forums: [DocumentForum]!
navbar: String!
dateCreated: Date!
publishStart: Date
publishEnd: Date
author: UserDetails!
group: Group!
media: [Media]!
tempId: Int!
viewsTotal: Int!
viewsMonth: Int!
searchable: Boolean!
available: Boolean!
cacheable: Boolean!
fileName: String
fileChange: Date
sortPriority: Int!
headerDocId: Int!
menuDocId: Int!
footerDocId: Int!
passwordProtected: String
htmlHead: String!
perexPlace: String!
perexImage: String!
perexGroup: String
showInMenu: Boolean!
eventDate: Date
virtualPath: String!
syncId: Int!
syncStatus: Int!
logonPageDocId: Int!
rightMenuDocId: Int!
fieldA: String!
fieldB: String!
fieldC: String!
fieldD: String!
fieldE: String!
fieldF: String!
fieldG: String!
fieldH: String!
fieldI: String!
fieldJ: String!
fieldK: String!
fieldL: String!
disableAfterEnd: Boolean!
forumCount: Int!
fieldM: String!
fieldN: String!
fieldO: String!
fieldP: String!
fieldQ: String!
fieldR: String!
fieldS: String!
fieldT: String!
requireSsl: Boolean!
rootGroupL1: Int
rootGroupL2: Int
rootGroupL3: Int
}
type Query {
findAllDocuments: [Document]!
}
This is the Query resolver class:
public class Query implements GraphQLQueryResolver {
private final DocumentRepository documentRepository;
private final DocumentForumRepository documentForumRepository;
private final GroupRepository groupRepository;
private final MediaRepository mediaRepository;
private final UserDetailsRepository userDetailsRepository;
#Autowired
public Query(DocumentRepository documentRepository,
DocumentForumRepository documentForumRepository,
GroupRepository groupRepository,
MediaRepository mediaRepository,
UserDetailsRepository userDetailsRepository){
this.documentRepository = documentRepository;
this.documentForumRepository = documentForumRepository;
this.groupRepository = groupRepository;
this.mediaRepository = mediaRepository;
this.userDetailsRepository = userDetailsRepository;
}
public Iterable<Document> findAllDocuments(){
return documentRepository.findAll();
}
public Iterable<DocumentForum> findAllDocumentForums(){
return documentForumRepository.findAll();
}
public Iterable<Group> findAllGroups(){
return groupRepository.findAll();
}
public Iterable<Media> findAllMedia(){
return mediaRepository.findAll();
}
}
And this is the DocumentResolver class:
public class DocumentResolver implements GraphQLResolver<Document> {
private DocumentForumRepository documentForumRepository;
private GroupRepository groupRepository;
private MediaRepository mediaRepository;
private UserDetailsRepository userDetailsRepository;
#Autowired
public DocumentResolver(DocumentForumRepository documentForumRepository,
GroupRepository groupRepository,
MediaRepository mediaRepository,
UserDetailsRepository userDetailsRepository){
this.documentForumRepository = documentForumRepository;
this.groupRepository = groupRepository;
this.mediaRepository = mediaRepository;
this.userDetailsRepository = userDetailsRepository;
}
public List<DocumentForum> getForums(Document document){
return documentForumRepository.findAllById(document.getId());
}
public UserDetails getAuthor(Document document) throws ObjectNotFoundException {
Optional<UserDetails> optionalUserDetails = userDetailsRepository.findById(document.getId());
if(optionalUserDetails.isPresent()){
return optionalUserDetails.get();
}else{
throw new ObjectNotFoundException();
}
}
public Group getGroup(Document document) throws ObjectNotFoundException {
Optional<Group> optionalGroup = groupRepository.findById(document.getId());
if(optionalGroup.isPresent()){
return optionalGroup.get();
}else{
throw new ObjectNotFoundException();
}
}
public List<Media> getMedia(Document document) {
return mediaRepository.findAllById(document.getId());
}
}
The query I try to send from Postman:
{
findAllDocuments{
id
title
data
}
}
Everything works in my smaller project and I can't pinpoint what's the problem here. If anything else is needed, please let me know and I'll provide it. Thank you.

Related

Spring specification query for one to many join and sum of field is grater then given value

I am creating filter using joining this three entity seeker_job_application,seeker_profile and seeker_experience. where I want achieve result as below query.
In filter I want to find out seeker_profile whose total_moth of experience should be grater then or equal to given value i.e 20, one seeker_profile has multiple experience so I need to group by profile and sum of their experience and then compare with given value. is it possible to do this using spring specification?
How to check that seeker total month of experience is grater then or equal to given value?
Relation between table is
seeker_job_application 1<-->1 seeker_profile 1<---->* seeker_experience
Want to achieve query like this
select r.sja_id,r.sp_id,r.name,r.company_name,r.total_month from (
select sja.id as sja_id , sp.id as sp_id , sp.`name`,se.company_name,sum(se.total_month) as total_month
from seeker_job_application sja
INNER JOIN seeker_profile sp on sp.id = sja.seeker_id
INNER JOIN seeker_experience se on se.seeker_id = sp.id
where job_id =1 group by sp.id ) as r where r.total_month > 20;
#Entity
#Table(name = "seeker_job_application")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SeekerJobApplication implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#NotNull
#Column(name = "seeker_id", nullable = false)
private Long seekerId;
#NotNull
#Column(name = "job_id", nullable = false)
private Long jobId;
#Column(name = "apply_date")
private Instant applyDate;
#Column(name = "profile_viewed")
private Boolean profileViewed;
#Column(name = "on_hold")
private Boolean onHold;
#Column(name = "interview_schedule")
private Boolean interviewSchedule;
#Column(name = "rejected")
private Boolean rejected;
#Column(name = "selected")
private Boolean selected;
#Column(name = "prefered_location_id")
private Long preferedLocationId;
#Column(name = "work_preference")
private String workPreference;
#Column(name = "resume_file_path")
private String resumeFilePath;
#Column(name = "status")
private String status;
#ManyToOne
#JoinColumn(name="seeker_id",referencedColumnName = "id", insertable = false, updatable = false)
private SeekerProfile seekerProfile;
#Data
#Entity
#Table(name = "seeker_profile")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SeekerProfile implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "id")
private Long id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "mobile_number", nullable = false)
private String mobileNumber;
#Column(name = "password")
private String password;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "house_number")
private String houseNumber;
#Column(name = "address_line_1")
private String addressLine1;
#Column(name = "address_line_2")
private String addressLine2;
#Column(name = "city")
private String city;
#Column(name = "postcode")
private String postcode;
#Column(name = "state")
private String state;
#Column(name = "country")
private String country;
#Column(name = "website")
private String website;
#Column(name = "linkedin")
private String linkedin;
#Column(name = "facebook")
private String facebook;
#Column(name = "gender")
private String gender;
#Column(name = "dob")
private String dob;
#Column(name = "resume")
private String resume;
#Column(name = "wfh")
private String wfh;
#Column(name = "profile_completed")
private String profileCompleted;
#OneToOne
#JoinColumn(unique = true)
private Location preferedLocation;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "seeker_skill", joinColumns = { #JoinColumn(name = "seeker_id") }, inverseJoinColumns = { #JoinColumn(name = "skill_id") })
private Set<Skill> skills;
#OneToMany(fetch = FetchType.EAGER)
#JoinColumn(name="seeker_id",referencedColumnName = "id", insertable = false, updatable = false)
private Set<SeekerExperience> seekerExperiences;
#OneToMany
#JoinColumn(name="seeker_id",referencedColumnName = "id", insertable = false, updatable = false)
private Set<SeekerEducation> seekerEducation;
#Entity
#Table(name = "seeker_experience")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SeekerExperience implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#NotNull
#Column(name = "seeker_id", nullable = false)
private Long seekerId;
#NotNull
#Column(name = "job_title", nullable = false)
private String jobTitle;
#NotNull
#Column(name = "company_name", nullable = false)
private String companyName;
#NotNull
#Column(name = "start_date", nullable = false)
private String startDate;
#NotNull
#Column(name = "end_date", nullable = false)
private String endDate;
#Column(name = "total_month")
private Integer totalMonth;
#Column(name = "location")
private String location;
#Column(name = "role_description")
private String roleDescription;
Specification<SeekerJobApplication> specification = Specification.where(null);
specification = specification.and((root, query, cb) -> {
Join<SeekerJobApplication, SeekerProfile> seekerProfile=root.join(SeekerJobApplication_.seekerProfile);
Join<SeekerProfile, SeekerExperience> seekerExperience = seekerProfile.join(SeekerProfile_.seekerExperiences);
query.having(cb.greaterThanOrEqualTo(cb.sum(seekerExperience.get(SeekerExperience_.totalMonth)), criteria.getTotalExperience().getEquals()));
query.getRestriction();
});
This will give me result as below query
select sja.* from seeker_job_application sja
INNER JOIN seeker_profile sp on sja.seeker_id = sp.id
INNER JOIN seeker_experience se on se.seeker_id = sp.id
where sja.job_id = 1
GROUP BY sp.id
having sum(se.total_month) > 20

Need to save/update child 500 or more rows in parent-child relationship with-in 10sec using Spring-Data-JPA

I have a scenario where I need to save or update 500 or more item in postgres db within 10sec using spring-data-jpa. below are my domain and service class.
GroupingForm.java
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode
#Entity
#Table(name = "GroupingForm")
public class GroupingForm implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "uuid", strategy = "uuid2")
#GeneratedValue(generator = "uuid")
#Column(name = "grouping_form_id",unique = true, nullable = false)
private UUID groupingFormId;
#Column(name = "grouping_form_name")
private String groupingFormName;
#Column(name = "vid")
private String vid;
#Column(name = "vendor_name")
private String vendorName;
#Column(name = "hovbu")
private String hovbu;
#Column(name = "fid")
private String fid;
#Column(name = "factory_name")
private String factoryName;
#Column(name = "item_count")
private Integer itemCount;
#CreationTimestamp
#Column(name = "creation_date")
private Timestamp creationDate;
#Column(name = "created_by")
private String createdBy;
#UpdateTimestamp
#Column(name = "modified_date")
private Timestamp modifiedDate;
#Column(name = "modified_by")
private String modifiedBy;
#Column(name = "product_engineer")
private String productEngineer;
#Column(name = "status")
private String status;
#Column(name = "sourcing_type")
private String sourcingType;
#Column(name = "total_comments")
private Integer totalComments;
#Column(name = "factory_name_chinese")
private String factoryNameChinese;
#Column(name = "grouping_form_type")
private String groupingFormType;//to save as Product/transit/Product_transit
#Column(name = "ref_id")
private String refId;
#JsonManagedReference
#OneToMany(mappedBy = "groupingForm", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ProductItemsMapping> productItems = new ArrayList<>();
#JsonManagedReference
#OneToMany(mappedBy = "groupingForm", cascade = CascadeType.ALL, orphanRemoval = true)
private List<TransitItemsMapping> transitItems = new ArrayList<>();
#Column(name = "pdf_status")
private String pdfStatus;
}
ProductItemsMapping.java
#Data
#Entity
#Table(name = "ProductItemsMapping")
public class ProductItemsMapping implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "uuid", strategy = "uuid2")
#GeneratedValue(generator = "uuid")
#Column(name = "product_item_id",unique = true, nullable = false)
private UUID productItemId;
#ToString.Exclude
#JsonBackReference
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "grouping_form_id")
private GroupingForm groupingForm;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(referencedColumnName = "dim_Item_ID",name = "item_id")
private Item item;
#Column(name ="item_relationship_id", insertable = false,updatable = false)
private String itemRelationshipId;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "item_relationship_id",referencedColumnName = "dim_item_relationship_id")
private VendorFactoryItem vendorFactoryItem;
#Column(name = "edam_id")
private String edamId;
#Column(name = "model_number")
private String modelNumber;
#Column(name = "description")
private String description;
#Column(name = "material")
private String material;
#Column(name = "finishing_colour")
private String finishingColour;
#Column(name = "dimensions")
private String dimensions;
#Column(name = "product_net_weight")
private String productNetWeight;
#Column(name = "insertion_order")
private Integer insertionOrder;
#Column(name = "comments")
private String comments;
#Column(name = "item_unique_id")
private String itemUniqueId;
}
TransitItemsMapping.java
#Data
#Entity
#Table(name = "TransitItemsMapping")
public class TransitItemsMapping implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "uuid", strategy = "uuid2")
#GeneratedValue(generator = "uuid")
#Column(name = "transit_Item_id",unique = true, nullable = false)
private UUID transitItemId;
#ToString.Exclude
#JsonBackReference
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "grouping_form_id")
private GroupingForm groupingForm;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(referencedColumnName = "dim_Item_ID",name = "item_id")
private Item item;
#Column(name ="item_relationship_id", insertable = false,updatable = false)
private String itemRelationshipId;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "item_relationship_id",referencedColumnName = "dim_item_relationship_id")
private VendorFactoryItem vendorFactoryItem;
#Column(name = "edam_id")
private String edamId;
#Column(name = "model_number")
private String modelNumber;
#Column(name = "description")
private String description;
#Column(name = "packaging_details")
private String packagingDetails;
#Column(name = "packaging_method")
private String packagingMethod;
#Column(name = "is_side_stack")
private String isSideStack;
#Column(name = "quantity")
private Integer quantity;
#Column(name = "dimensions")
private String dimensions;
#Column(name = "product_net_weight")
private String productNetWeight;
#Column(name = "plastic_bag_ind")
private String plasticBagInd;
#Column(name = "insertion_order")
private Integer insertionOrder;
#Column(name = "comments")
private String comments;
#Column(name = "item_unique_id")
private String itemUniqueId;
#Column(name = "itm_pak_qty")
private Integer itemPackQuantity;
}
Item.java
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode
#Entity
#Table(name = "Item")
public class Item implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
//#GenericGenerator(name = "uuid", strategy = "uuid2")
//#GeneratedValue(generator = "uuid")
#JsonIgnore
#Column(name = "dim_Item_ID", unique = true, nullable = false)
private UUID dimItemId;
//mdm columns start
#Valid
#EmbeddedId
private ItemId itemId;
#Column(name = "model")
private String model;
#Column(name = "description")
private String description;
#CreationTimestamp
#Column(name="effective_date")
private Timestamp effectiveDate;
#JsonIgnore
#Column(name="expiration_date")
private Timestamp expirationDate;
#JsonIgnore
#Column(name="business_area_number")
private Integer businessAreaNumber;
#JsonIgnore
#Column(name="business_area_desc")
private String businessAreaDesc;
#JsonIgnore
#Column(name="division_number")
private Integer divisionNumber;
#JsonIgnore
#Column(name="division_desc")
private String divisionDesc;
#JsonIgnore
#Column(name="sub_division_number")
private Integer subDivisionNumber;
#JsonIgnore
#Column(name="sub_division_desc")
private String subDivisionDesc;
#JsonIgnore
#Column(name="product_group_number")
private Integer productGroupNumber;
#JsonIgnore
#Column(name="product_group_desc")
private String productGroupDesc;
#JsonIgnore
#Column(name="assortment")
private Integer assortment;
#JsonIgnore
#Column(name="assortment_desc")
private String assortmentDesc;
#JsonIgnore
#Column(name="status")
private Integer status;
#JsonIgnore
#Column(name="status_desc")
private String statusDesc;
#Column(name = "origin_country")
private String originCountry;
#Column(name = "destination_country")
private String destinationCountry;
#Column(name = "is_private_brand")
private String isPrivateBrand;
#Column(name = "brand")
private String brandName;
#Column(name = "item_weight")
private Double itemWeight;
#Column(name = "in_box_height")
private Double inBoxHeight;
#Column(name = "in_box_width")
private Double inBoxWidth;
#Column(name = "in_box_depth")
private Double inBoxDepth;
#Column(name = "primary_image")
private String primaryImage;
#Column(name = "component_materials")
private String componentMaterials;
#Column(name = "product_detail")
private String productDetail;
#Column(name = "finishing_color")
private String finishingColor;
#Column(name = "packaging_method")
private String packagingMethod;
#Column(name = "packaging_quantity")
private Integer packagingQuantity;
#Column(name = "out_box_depth")
private Double outBoxDepth;
#Column(name = "out_box_height")
private Double outBoxHeight;
#Column(name = "out_box_width")
private Double outBoxWidth;
#Column(name = "net_weight")
private Double netWeight;
#Column(name = "plastic_bag_ind")
private String plasticBagInd;
//mdm columns ends
//Adhoc specific start
#JsonIgnore
#Column(name="is_current")
private Integer isCurrent;
#JsonIgnore
#Column(name="remark")
private String remark;
#JsonIgnore
#Column(name="is_valid")
private String isValid;
#CreationTimestamp
#Column(name="creation_date")
private Timestamp creationDate;
#JsonIgnore
#Column(name="created_by")
private String createdBy;
#JsonIgnore
#UpdateTimestamp
#Column(name="last_modified_date")
private Timestamp lastModifiedDate;
#Column(name = "is_adhoc_item")
private String isAdhocItem;
//Adhoc specific ends
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
private List<VendorFactoryItem> vendorFactoryItems;
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
private List<ProductItemsMapping> productItems = new ArrayList<>();
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
private List<TransitItemsMapping> transitItems = new ArrayList<>();
#Transient
#JsonIgnore
private Integer itemNumber;
#Transient
#JsonIgnore
private String itemRelationshipId;
#Transient
#JsonIgnore
private String vendorId;
#Transient
#JsonIgnore
private String retailer;
#Transient
#JsonIgnore
private String fid;
#Transient
#JsonIgnore
private String hovbu;
#Column(name="sourcing_type")
private String sourcingType;
#Column(name = "itm_pak_qty")
private Integer itemPackQuantity;
#Column(name = "barcode")
private String barcode;
#Column(name = "item_type")
private String itemType;
#Column(name = "item_cube")
private String itemCube;
}
VendorFactoryItem.java
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode
#Entity
#Builder
#Table(name = "vendorfactoryitem")
public class VendorFactoryItem implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EmbeddedId
private VendorFactoryItemId vendorFactoryItemId;
#JsonIgnore
#Column(name = "dim_item_relationship_id")
private String itemRelationshipId;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "hovbu",updatable = false,insertable = false),
#JoinColumn(name = "item_number",updatable = false,insertable = false),
#JoinColumn(name = "retailer",updatable = false,insertable = false)
})
private Item item;
#Column(name = "item_id")
private String itemIdRel;
#Column(name = "is_adhoc_rel")
private String isAdHocRel;
#Column(name = "dim_factory_import_id")
private String dimFactoryImportId;
#Column(name = "factory_short_name")
private String factoryShortName;
#Column(name = "company_id")
private String companyId;
#Column(name = "vendor_short_name")
private String vendorShortName;
#Column(name = "remark")
private String remark;
#Column(name = "is_valid")
private String isValid;
#Column(name = "created_on")
private Timestamp createdOn;
#Column(name = "created_by")
private String createdBy;
#Column(name = "last_modified_date")
private Timestamp lastModifiedDate;
#Column(name = "effective_date")
private Timestamp effectiveDate;
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "vendorFactoryItem")
private List<ProductItemsMapping> productItems = new ArrayList<>();
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "vendorFactoryItem")
private List<TransitItemsMapping> transitItems = new ArrayList<>();
}
GroupingFormRepository.java
#Repository
public interface GroupingFormRepository
extends JpaRepository<GroupingForm, UUID>, GroupingFormRepositoryCustom {
}
GroupingFormService.java
#Transactional
public GroupingFormDto saveGroupingFormV1(GroupingFormDto groupingFormDto) {
//do the mapping DTO to DOMAIN..remove the code ..
**GroupingForm groupingFormSaved = groupingFormRepository.save(groupingForm);**
}
With in the GroupingForm object I am setting the transitItem and productItem to save or update. And also adding Item and VendorfactoryItems not for save or update. what are the best way I can optimize this save and update with in 10 sec while I am passing more than 500 productItem and 500 transitItem.
Thanks in advance.

Manytoone mapping for two tables to the single entity

Class A{
private int campid;
private string name;
}
Class B {
Private int campid;
Private string name;
}`
Class combo{
private int id;
private string phonenumber;
}
I'm trying like this
Class A{
private int campid;
private string name;
#OneToMany(targetEntity = Combo.class,mappedBy ="a",fetch = FetchType.LAZY,cascade=CascadeType.ALL )
private Combo combo;
}
Class B {
Private int campid;
Private string name;
#OneToMany(targetEntity = Combo.class,mappedBy ="b",fetch = FetchType.LAZY,cascade=CascadeType.ALL )
private Combo combo;
}`
Class combo{
private int id;
private string phonenumber;
#ManyToOne
#JoinColumn(name = "Camp_Id_fk",insertable=true, updatable=true)
private A a;
#ManyToOne
#JoinColumn(name = "Camp_Id_fk",insertable=true, updatable=true)
private B b;
}
want to store the campid of class A and campid class B as the foreign key in the combo table. One campid can have multiple phone numbers.
I want to do this in spring jpa..I'm not understanding how to do it
#Entity
#Table(name = "a")
public class A {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "camp_id")
private Long campid;
#Column(name = "name")
private String name;
#Column
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
#JoinTable(name = "a_combo",
joinColumns = #JoinColumn(name = "camp _id"),
inverseJoinColumns = #JoinColumn(name = "id"))
private Set<Combo> comboSet = new HashSet<>();
}
And same for B class

Get Max Value with Spring-JPA

I want do query to my table with spring-JPA (I can't use #Query) for get the max register
The query have any conditions:
Initially my query get register where version is "x" and Validated is 1 and the process is a list.
version: "1A"
validated: 1 -> It is always 1.
lista: ["process1","process2"] or with 3,4 process...
myRepo.findByIdVersionCierreAndAndValidatedAndIdProcessIn(version, 1, lista);
But In my database I can be two registers:
1º
version: "1A"
validated: 1
lista: ["process1","process2"]
Exec: 1
2º
version: "1A"
validated: 0
lista: ["process1","process2"]
Exec: 2
I need get the register with max Exec, because in my register 1º, validated is 1, BUT in my register 2, validated is 0 y con my old code, I get the register Exec1 - "myRepo.findByIdVersionCierreAndAndValidatedAndIdProcessIn(version, 1, lista);"
First I saw the post:
Spring CRUD repository: is there findOneByMaxXYZColumn()?
So I modified my code:
myRepo.findFirstfindByIdVersionCierreAndAndValidatedOrderbyIdExecDescAndIdProcessIn(version, 1, lista);
Err:
Caused by: java.lang.IllegalArgumentException: Failed to create query method public abstract java.util.List es.repository.DataValidationRepository.findFirstfindByIdVersionCierreAndAndValidatedOrderbyIdExecDescAndIdProcessIn(java.lang.String,int,java.util.List)! No property orderbyIdExecDesc found for type int! Traversed path: TpValidaAuto.validated.
And
myRepo.findFirstfindByIdVersionCierreAndAndValidatedAndIdProcessInOrderbyIdExecDesc(version, 1, lista);
however I get a error when I run the SpringBoot:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property inOrderbyIdExecDesc found for type String! Traversed path: TpValidaAuto.idProcess.
EDIT:
#Repository
public interface DataValidationRepository extends CrudRepository<TpValidaAuto, String> {
List<TpValidaAuto> findByIdVersionCierreAndAndValidatedAndIdProcessIn(String version, int validated, List<String> process);
}
Entity:
#Entity
#Table(name = "MyTable")
#GETTER
#SETTER
public class TpValidaAuto {
#Id
#NotNull
#Column(name = "ID")
#JsonProperty("id")
private String id;
#NotNull
#Column(name = "ID_FICHERO")
#JsonProperty("file")
private String idFile;
#NotNull
#Column(name = "ID_EJECUCION")
#JsonProperty("exec")
private int idExec;
#NotNull
#Column(name = "ID_PROCESO")
#JsonProperty("process")
private String idProcess;
#Column(name = "ID_PERIODO")
#JsonProperty("period")
private String idPeriod;
#Column(name = "FC_ULT_DATO")
#JsonProperty("lastdatedata")
private String lastDateData;
#Column(name = "IND_INCLUIR_CIERRE")
#JsonProperty("validated")
#JsonFormat(shape = JsonFormat.Shape.BOOLEAN)
private int validated;
#Column(name = "ID_VERSION_CIERRE")
#JsonProperty("lastdateclose")
private String idVersionCierre;
#NotNull
#Column(name = "IND_DATOS_MODIF")
#JsonProperty("modificated")
private int modificated;
#NotNull
#Column(name = "FC_ALTA")
#JsonProperty("createDate")
private String createDate;
#NotNull
#Column(name = "USR_ALTA")
#JsonProperty("createUser")
private String createUser;
#NotNull
#Column(name = "FC_MODIFICACION")
#JsonProperty("modificationDate")
private String modificationDate;
#NotNull
#Column(name = "USR_MODIFICACION")
#JsonProperty("modificationUser")
private String modificationUser;
#JsonGetter("validated")
public boolean validated() {
boolean result = true;
if (this.validated == 0) {
result = false;
}
return result;
}
#JsonSetter("validated")
public void validated(boolean validated) {
if (validated) {
this.validated = 1;
} else {
this.validated = 0;
}
}

jpa findby with list of conditions

I am still a beginner with java, here I'm trying to fetch the data from mysql database using JPA.
but I'm getting a problem with setting the list of conditions with find by function.
i can set Object of date even it refused the inputs
below is my code for reference.
my query :
select t.id, t.MSISDN, t.Param1, t.param2
from BULK_REPOSITORY t
where t.Camp_Start_Date between Sysdate - 2 and sysdate
and t.status = 0
and t.camp_type = 1;
Application :
#SpringBootApplication
public class AccessingDataJpaApplication {
private static final Logger log = LoggerFactory.getLogger(AccessingDataJpaApplication.class);
Bulk_repository bulk ;
public static void main(String[] args) {
SpringApplication.run(AccessingDataJpaApplication.class);
}
#Bean
public CommandLineRunner demo(Bulk_repositoryRepository repository) {
return (args) -> {
// fetch customers by Status
log.info("Customer found with findByStatus('0'):");
log.info("--------------------------------------------");
repository.findAllByStatusAndCampTypeAndCampStart_dateBetween(1,2,Date,Date-2).forEach(on -> {
log.info(on.toString());
});
};
}
Bulk_repositoryRepository class :
import org.springframework.data.repository.CrudRepository;
public interface Bulk_repositoryRepository extends CrudRepository<Bulk_repository, Long> {
List<Bulk_repository> findAllByStatusAndCampTypeAndCampStart_dateBetween(int status, int campType,Date campStart_dateStart, Date campStart_dateEnd);
Bulk_repository findById(long id);
}
Bulk_repository:
#Entity
#Table(name = "BULK_REPOSITORY")
public class Bulk_repository {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "msisdn")
private String msisdn;
#Column(name = "camp_start_date")
private Date campStartDate;
#Column(name = "camp_end_date")
private Date campEndDate;
#Column(name = "camp_type")
private int campType;
#Column(name = "camp_cd")
private String camp_cd;
#Column(name = "status")
private int status;
#Column(name = "process_date")
private Date processDate;
#Column(name = "entry_date")
private Date entryDate;
#Column(name = "entry_user")
private String entry_user;
#Column(name = "param1")
private String param1;
#Column(name = "param2")
private String param2;
#Column(name = "param3")
private String param3;
#Column(name = "param4")
private String param4;
#Column(name = "param5")
private String param5;
#Column(name = "error_desc")
private String error_desc;
#Column(name = "fulfilment_status")
private int fulfilment_status;
## getter and setter and ToString
Use this way,
Escape the _ by using an additional underscore
List<Bulk_repository> findAllByStatusAndCamp__typeAndCamp__start__dateBetween(int status, int camp_type,Date camp_start_dateStart, Date camp_start_dateEnd);
I recommond to use this way in your model class. If so you have to change your repository according to this.
#Column(name = "camp_start_date")
private Date campStartDate; // better to use this way

Resources