Insert data into three table by using JPA #onetomany and #manytoone annotation - spring-boot
I am trying to insert data into three different tables by using JPA Repository with spring boot application. for this purpose i used #onetomany and #manytoone annotation in these three classes:
HouseHold
OwnerDetails
HouseHoldMembers
but when i am trying to insert i am getting the following error.
Hibernate:
select
*
from
household
where
sl_no = ?
2019-10-16 12:24:46.622 INFO 19380 --- [nio-8080-exec-1] c.o.a.a.s.FormServiceImpl : FormServiceImpl saveHouseDetailsWithBase64() is invoked : 234546674
Hibernate:
select
nextval ('house_id_seq')
Hibernate:
select
nextval ('owner_id_seq')
Hibernate:
select
nextval ('mem_id_seq')
Hibernate:
insert
into
household
(area, audio, district, east, gp_name, grid_no, house_dimension, house_photo, id, id_number, id_photo, Khatha_no, latitute, locality_name, longitute, map_photo, north, phone_num, pin, prop_details, prop_type, rent_amount, road_name, sl_no, south, servey_date, survey_no, surveyor_name, taluk, tenant, toilet_available, total_members, vacant_port, village_name, water_facility, west, hid)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate:
insert
into
ownerdetails
(age, education, gender, hid, idname, idnumber, name, oid)
values
(?, ?, ?, ?, ?, ?, ?, ?)
2019-10-16 12:24:46.832 WARN 19380 --- [nio-8080-exec-1] o.h.e.j.s.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2019-10-16 12:24:46.832 ERROR 19380 --- [nio-8080-exec-1] o.h.e.j.s.SqlExceptionHelper : ERROR: null value in column "hid" violates not-null constraint
Detail: Failing row contains (1, 10, education, male, adhaarcard1, 23424242343, name, null).
2019-10-16 12:24:46.840 ERROR 19380 --- [nio-8080-exec-1] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
could not execute statement; SQL [n/a]; constraint [hid]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
2019-10-16 12:24:46.848 ERROR 19380 --- [nio-8080-exec-1] c.o.a.a.s.FormServiceImpl : could not execute statement; SQL [n/a]; constraint [hid]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
2019-10-16 12:24:46.849 INFO 19380 --- [nio-8080-exec-1] c.o.a.a.c.FormDataController : FormDataController saveHouseHold() request is completed.
HouseHold.java
#Entity
#Table(name = "household")
public class HouseHold implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "house_id_seq")
#SequenceGenerator(name = "house_id_seq", sequenceName = "house_id_seq", allocationSize = 1)
#Column(name = "hid")
private Long hid;
#NotNull
#Size(max = 100)
#Column(name = "district")
private String district;
#NotNull
#Size(max = 100)
#Column(name = "taluk")
private String taluk;
#NotNull
#Size(max = 100)
#Column(name = "village_name")
private String villageName;
#NotNull
#Column(name = "sl_no")
private Long slNo;
#NotNull
#Size(max = 100)
#Column(name = "Khatha_no")
private String khathaNo;
#NotNull
#Size(max = 50)
#Column(name = "locality_name")
private String localityName;
#NotNull
#Size(max = 50)
#Column(name = "prop_details")
private String propertyDetails;
#NotNull
#Size(max = 50)
#Column(name = "tenant")
private String tenant;
#NotNull
#Size(max = 200)
#Column(name = "house_dimension")
private String houseDimension;
#NotNull
#Size(max = 50)
#Column(name = "east")
private String east;
#NotNull
#Size(max = 50)
#Column(name = "west")
private String west;
#NotNull
#Size(max = 50)
#Column(name = "north")
private String north;
#NotNull
#Size(max = 50)
#Column(name = "south")
private String south;
#NotNull
#Digits(integer = 6, fraction = 2)
#Column(name = "rent_amount")
private BigDecimal rentAmount;
#NotNull
#Size(max = 100)
#Column(name = "vacant_port")
private String vacantPort;
#NotNull
#Size(max = 100)
#Column(name = "gp_name")
private String gpName;
#NotNull
#Size(max = 100)
#Column(name = "prop_type")
private String propertyType;
#NotNull
#Size(max = 100)
#Column(name = "road_name")
private String roadName;
#NotNull
#Column(name = "pin")
private Long pin;
#NotNull
#Column(name = "survey_no")
private Long surveyNo;
#NotNull
#Size(max = 250)
#Column(name = "grid_no")
private String gridNo;
#NotNull
#Size(max = 250)
#Column(name = "id_number")
private String idNumber;
#NotNull
#Size(max = 100)
#Column(name = "area")
private String area;
#NotNull
#Size(max = 3)
#Column(name = "toilet_available")
private String toiletAvailable;
#NotNull
#Size(max = 3)
#Column(name = "water_facility")
private String waterFacility;
#NotNull
#Column(name = "phone_num")
private Long phoneNumber;
#NotNull
#Column(name = "house_photo")
private String housephoto;
#NotNull
#Column(name = "id_photo")
private String idphoto;
#NotNull
#Column(name = "map_photo")
private String mapphoto;
#NotNull
#Column(name = "audio")
private String audio;
#NotNull
#Digits(integer = 3, fraction = 25)
#Column(name = "latitute")
private BigDecimal latitude;
#NotNull
#Digits(integer = 3, fraction = 25)
#Column(name = "longitute")
private BigDecimal longitude;
#NotNull
#Size(max = 100)
#Column(name = "surveyor_name")
private String surveyorName;
#Column(name = "servey_date")
#Temporal(TemporalType.TIMESTAMP)
private Date surveyDate;
#NotNull
#Size(max = 10)
#Column(name = "total_members")
private String totalMembers;
#NotNull
#Column(name = "id")
private Long id;
#JsonIgnore
#Transient
private String serveyStringDate;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "houseHold", fetch = FetchType.EAGER)
private List<OwnerDetails> ownerdetail = new ArrayList<>();
//default constructor
//parameterized constructor
//getter setter
OwnerDetails.java
#Entity
#Table(name = "ownerdetails")
public class OwnerDetails implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "owner_id_seq")
#SequenceGenerator(name = "owner_id_seq", sequenceName = "owner_id_seq", allocationSize = 1)
#Column(name = "oid")
private Long oid;
#NotNull
#Size(max = 100)
#Column(name = "name")
private String name;
#NotNull
#Size(max = 100)
#Column(name = "education")
private String education;
#NotNull
#Column(name = "age")
private int age;
#NotNull
#Size(max = 10)
#Column(name = "gender")
private String gender;
#NotNull
#Size(max = 100)
#Column(name = "idname")
private String idName;
#NotNull
#Size(max = 100)
#Column(name = "idnumber")
private String idNumber;
#JsonIgnore
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "hid", referencedColumnName = "hid", nullable = false, updatable = false, insertable = true)
#OnDelete(action = OnDeleteAction.CASCADE)
private HouseHold houseHold;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ownerdetails", fetch = FetchType.EAGER)
private List<HouseHoldMembers> membersdetails = new ArrayList<>();
//default constructor
//parameterized constructor
//getter setter
HouseHoldMembers.java
#Entity
#Table(name = "household_members")
public class HouseHoldMembers implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "mem_id_seq")
#SequenceGenerator(name = "mem_id_seq", sequenceName = "mem_id_seq", allocationSize = 1)
#Column(name = "mid")
private Long mid;
#NotNull
#Size(max = 100)
#Column(name = "name")
private String name;
#NotNull
#Size(max = 100)
#Column(name = "education")
private String education;
#NotNull
#Column(name = "age")
private int age;
#NotNull
#Size(max = 10)
#Column(name = "gender")
private String gender;
#NotNull
#Size(max = 100)
#Column(name = "idname")
private String idName;
#NotNull
#Size(max = 100)
#Column(name = "idnumber")
private String idNumber;
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "oid", nullable = false, updatable = false, insertable = true)
#OnDelete(action = OnDeleteAction.CASCADE)
private OwnerDetails ownerdetails;
//default constructor
//parameterized constructor
//getter setter
Dtat.json
{
"district" : "district",
"taluk" : "taluk",
"villageName" : "village name",
"slNo" : 234546674,
"khathaNo" : "35824005",
"localityName" : "localitiyname",
"propertyDetails" : "property Details",
"tenant" : "tenant",
"houseDimension" : "housedimension",
"east":"east",
"west":"west",
"north":"north",
"south":"south",
"rentAmount":2000.45,
"vacantPort":"2342",
"gpId":23112,
"gpName":"gpname",
"propertyType":"proprty type",
"roadName":"road name",
"pin":700003,
"surveyNo":23122,
"gridNo":"23122",
"idNumber":"2321223232232",
"area":"area",
"toiletAvailable":"yes",
"waterFacility":"yes",
"phoneNumber":9999999999,
"housephoto":"",
"mapphoto":"",
"audio":"",
"latitude":"22.453",
"longitude":"88.453",
"surveyorName":"surveyor name",
"serveyStringDate":"2019-10-13 11:25:36",
"totalMembers":"2",
"id":1,
"ownerdetail":
[
{
"name":"name",
"education":"education",
"age":10,
"gender":"male",
"idName":"adhaarcard1",
"idNumber":"23424242343",
"membersdetails":
[
{
"name":"name",
"education":"education",
"age":10,
"gender":"male",
"idName":"adhaarcard2",
"idNumber":"23424242344"
},
{
"name":"name1",
"education":"education1",
"age":11,
"gender":"male",
"idName":"adhaarcard2",
"idNumber":"23424242344"
}
]
}
]
}
also i created repository classes for each entity class. Can someone please help me to solve this error. Thank You in Advance.
[JPA Examplem][One to many and many to one relationship][https://github.com/kuldeepjha/JpaProject/tree/master/demo ]
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.
Why hibernate is throwing constraintViolationException?
Order Entity #Entity #Table(name = "Order", indexes = { #Index(name = "ORDER_X1", columnList = "REFERENCE_ID,SOURCE_ID"), #Index(name = "ORDER_X2", columnList = "TYPE,STATUS") } ) #DiscriminatorColumn(name="PROCESSOR_TYPE", discriminatorType=DiscriminatorType.STRING, length = 80) #SequenceGenerator(name="orderSeq", sequenceName="ORDER_SEQ") #Inheritance(strategy= InheritanceType.JOINED) public abstract class OrderEntity implements Serializable { #Id #GeneratedValue(strategy= GenerationType.SEQUENCE, generator="orderSeq") private Long id; #ManyToMany(cascade={CascadeType.MERGE}) #JoinTable( name = "FILE_ORDER_MAP", joinColumns = {#JoinColumn(name = "ORDER_ID")}, inverseJoinColumns = {#JoinColumn(name = "FILE_ID")} ) private Set<TransferFile> transferFiles = new HashSet<>(); #Column(name = "TYPE") #Enumerated(EnumType.STRING) private OrderType type; #Column(name = "AMOUNT", precision = 12, scale = 2) private LcMoney amount; #Column(name = "STATUS") #Enumerated(EnumType.STRING) private OrderStatus reconStatus; #Type(type = LcUtc.JPA_JODA_TIME_TYPE) #Column(name = "STATUS_D", nullable = false) #LcDateTimeUtc() private DateTime reconStatusDate; #Column(name = "REFERENCE_ID") private Long referenceId; #Column(name = "SOURCE_ID") private Long sourceId; #Column(name = "ACCOUNT_ID") private Long accountId; #Column(name = "PROCESSOR_TYPE", insertable = false, updatable = false) #Enumerated(EnumType.STRING) private OrderProcessorType processorType; #Type(type = LcUtc.JPA_JODA_TIME_TYPE) #Column(name = "TX_EXECUTION_D") #LcDateTimeUtc() private DateTime executedDate; #Type(type = LcUtc.JPA_JODA_TIME_TYPE) #Column(name = "CREATE_D") #LcDateTimeUtc() private DateTime createDate; #Column(name = "IS_ON_DEMAND") #Type(type = "yes_no") private boolean isOnDemand; #ManyToOne(fetch = FetchType.LAZY, optional = true, cascade = {CascadeType.PERSIST}) #JoinColumn(name="PAYER_ID", nullable=true) private Payer payer; #OneToMany(cascade = CascadeType.ALL) #JoinColumn(name = "ORDER_ID", referencedColumnName = "ID") private List<OrderTransaction> orderTransactions; #OneToMany(cascade = {CascadeType.ALL}) #JoinColumn(name = "ORDER_ID", referencedColumnName = "ID", foreignKey = #ForeignKey(name = "FK_ORDER") ) private List<MatchResult> matchResults; #Version #Column(name = "VERSION") private Integer version; #Embedded #AttributeOverrides({ #AttributeOverride(name = "externalSourceId", column = #Column(name = "TRANS_EXT_SRC_ID")), #AttributeOverride(name = "externalId", column = #Column(name = "TRANS_EXT_REF_ID")) }) private LcExternalIdEntity transExtId; #PreUpdate #PrePersist public void beforePersist() { if (reconStatusDate != null) { reconStatusDate = reconStatusDate.withZone(DateTimeZone.UTC); } if (executedDate != null) { executedDate = executedDate.withZone(DateTimeZone.UTC); } if (createDate != null) { createDate = createDate.withZone(DateTimeZone.UTC); } } // getters and setters } //controller method public Response processFile(){ // separate trasaction service.readFileAndCreateOrders(); // read files and create orders in new status List<Order> newOrders = service.getNewOrders(); for( Order order: newOrders){ service.processOrder(order); // separate transaction } } #Transaction void processOrder(OrderEntity order){ matchResultJpaRepository.save(orderEntity.id); log.info("Saving matchId={} for order={}", match.getId(), order.getId()); // create new transaction and add to order OrderTransaction transaction = createNewTransaction(order); order.getTransactions().add(transaction); order.setStatus("PROCESSED"); log.info("Saving Order id={}, Type={}, Status={} ", order.getId(), order.getType(), order.getStatus()); orderRepository.save(order); } I am seeing this below error. ORA-01407: cannot update ("PAYMENTS"."MATCH_RESULT"."ORDER_ID") to NULL This endpoing is not exposed to user. There is a batch job which invokes this endpoint. This code has been there for atleast a year and this is the first time i am seeing this. This happened only once and for only one call. I am seeing both the logs printed. I am puzzled why I am seeing above error complaining about NULL order id. From the logs, we can confirm that the order id is definitely not null. Any idea why this is happening? What can be done to fix this?
JPA Foreign Key in #OnetoOne relationship not showing up in Query
I am trying to create a #OneToOne relationship between FacilityGeneral and FacilityLocation Entitys wherein the FacilityLocation Entity owns the foreign key. I am able to start the application without any errors but when I query the FacilityGeneral entity using the built in findAll() statement, the named field (foreign key) isn't shown as a field value. The values do exist in the the database table. Whats happening here? FacilityGeneral Entity: #Entity public class FacilityGeneral { #Id #GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "facilityGenIdSeq") #SequenceGenerator(name = "facilityGenIdSeq", initialValue = 567, allocationSize = 1) #Column(updatable = false, unique = true) private Long generalIdPk; #NotBlank(message = "Facility Name is required") private String facilityName; #Column(length = 200) private String facilityNameHistory; #Column(length = 15) private String phoneNumber; private Integer phoneExtension; #Column(length = 50) private String facilityType; #Column(length = 50) private String facilityApprovalType; #Column(length = 50) private String landfillClass; #Column(length = 50) private String facilityStatus; #Column(length = 50) private String firstReceiptOfWaste; //This is a String because legacy data is inconsistent (some only years, others full dates) #Column(length = 50) private String ownershipType; #Column(length = 50) private String dshwStaffPerson; #Column(length = 50) private String legAndGovApproval; #JsonFormat(pattern = "MM/dd/yyyy") private LocalDate dateOfLegApproval; #JsonFormat(pattern = "MM/dd/yyyy") private LocalDate dateOfGovApproval; #Column(length = 200) private String govLegHyperlink; #JsonFormat(pattern = "MM/dd/yyyy") private LocalDate localApprovalDate; private String localApprovalDescription; #Column(length = 500) private String comments; #Column(length = 50) private String tireRegistrationNumber; #Column(length = 50) private String tireRegistrationFeePaid; #Column(length = 50) private String tireRegAppTrackingNumber; /*Tire Registration Application Tracking Numner*/ #JsonFormat(pattern = "MM/dd/yyyy") private LocalDate tireRegInsActivationDate; /*Tire Registration Insurance Application Date*/ #JsonFormat(pattern = "MM/dd/yyyy") private LocalDate tireRegInsExpirationDate; /*Tire Registration Insurance Expiration Data*/ #OneToOne(fetch = FetchType.EAGER, mappedBy = "facilityGeneral", cascade = CascadeType.PERSIST) private FacilityLocation location; Facility Location Entity #Entity public class FacilityLocation { #Id #SequenceGenerator(name = "facilityLocationSeq", initialValue = 374, allocationSize = 1) #GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "facilityLocationSeq") #Column(updatable= false, nullable = false, unique = true) private Long locationIdPk; #OneToOne (fetch = FetchType.EAGER) #JoinColumn (name="facilityIdFk", referencedColumnName ="generalIdPk", nullable = false) #JsonIgnore private FacilityGeneral facilityGeneral; private Double latitudeDegrees; private Double latitudeMinutes; private Double latitudeSeconds; private Double longitudeDegrees; private Double longitudeMinutes; private Double longitudeSeconds; private Double northing; private Double easting; private Double xCoordinate; private Double yCoordinate; private String descriptiveDirections; private String county; private String healthDepartment; private String healthDepartContact; private String facilityAddressStreet; private String facilityAddressCity; private Integer facilityZipFiveDigit; private Integer facilityZipFourDigit; private Integer townshipNumber; private String townshipDirection; private Integer rangeNumber; private String rangeDirection; private String section; private String quarterSection; private String qtrQtrSection; private String baseline; #JsonFormat(pattern = "MM/dd/yyyy") private LocalDate created_on; private Integer politicalDistrictHouse; private Integer politicalDistrictSenate; private String comments; private Double latitudeDecimalDegrees; private Double longitudeDecimalDegrees; Resulting Object from FacilityLocation Query does NOT contain the facilityIdFk field that I need: { "locationIdPk": 53, "latitudeDegrees": 38, "latitudeMinutes": 10, "latitudeSeconds": 10.16, "longitudeDegrees": 100, "longitudeMinutes": 10, "longitudeSeconds": 10.10, "northing": 0.000, "easting": 0.00, "xCoordinate": 000.0000, "yCoordinate": 4241085.372, "descriptiveDirections": "Approximately three miles northwest of Beaver and one mile east of Interstate 15", "county": "Beaver", "healthDepartment": "Public Health Department", "healthDepartContact": null, "facilityAddressStreet": null, "facilityAddressCity": "Beaver", "facilityZipFiveDigit": 0, "facilityZipFourDigit": 0, "townshipNumber": 29, "townshipDirection": "S", "rangeNumber": 7, "rangeDirection": "W", "section": "8", "quarterSection": "NW", "qtrQtrSection": "NE", "baseline": "SLBM", "created_on": "07/03/2006", "politicalDistrictHouse": null, "politicalDistrictSenate": 28, "comments": "Facility is located in the NE of the NW, the SE of the NW, and the NE of the NE quarter of section 8", "latitudeDecimalDegrees": 0.000, "longitudeDecimalDegrees": 0.000, "modified_on": null },
SpringBoot: How to rollback creation of parent if child creation fails?
I have two models namely Company and User. A Company can have many Users. I use Spring data jpa to interact with the database. User Model : #Entity public class User { #Id #GeneratedValue(strategy = GenerationType.AUTO) private Long id; #Column(length = 50, unique = true) #NotNull #Size(min = 4, max = 50) private String username; #NotNull #Size(min = 8) private String password; #Column(length = 50) #NotNull #Size(min = 4, max = 50) private String firstName; #Column(length = 50) #NotNull #Size(min = 4, max = 50) private String lastName; #Column(length = 50, unique = true) #NotNull #Size(min = 4, max = 50) private String email; private Boolean enabled = true; #Temporal(TemporalType.TIMESTAMP) #UpdateTimestamp private Date lastPasswordReset; #Column(nullable = false, updatable = false) #Temporal(TemporalType.TIMESTAMP) #CreatedDate private Date createdAt = new Date(); #Column(nullable = false) #Temporal(TemporalType.TIMESTAMP) #UpdateTimestamp #LastModifiedDate private Date updatedAt = new Date(); #ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) #JoinTable( name = "user_authority", joinColumns = {#JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {#JoinColumn(name = "authority_id", referencedColumnName = "id")}) private List<Authority> authorities; #ManyToOne(optional = false, fetch = FetchType.LAZY, cascade = CascadeType.REMOVE) #JsonBackReference private Company company; ... Getter and Setters } Company Model #Entity public class Company { #Id #GeneratedValue(strategy = GenerationType.AUTO) private Long id; #NotNull #Size(min = 4, max = 100) private String name; #Size(max = 500) private String description; #OneToMany(mappedBy = "company", cascade = CascadeType.ALL) #JsonManagedReference private List<User> users = new ArrayList<>(); ...Followed by Getter and Setters } So I use Spring Data JPA to save Company which takes care of creating a User as well. So today if for some reason the creation of user fails due to some exception, the company record still exists. So I need that if creation of User fails the Company shall not be created(rollback). How can I achieve this.