I'm setting an API endpoint that updates an existing user detail, to do that I try to fetch an existing user from the database by id, when I start the application and test with postman it runs the query on my console but displays TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing and fails to make the intended updates. Here is my code
Member
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name ="member",
indexes = {
#Index(
columnList = "email_address",
name = "email_address_idx",
unique = true
),
},
uniqueConstraints = {
#UniqueConstraint(
columnNames = {"email_address", "phone_number"},
name = "email_address_phone_number_uq"
)
}
)
public class Member {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "first_name", nullable = false)
private String firstName;
#Column(name = "last_name", nullable = false)
private String lastName;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "nationality_id")
private Country nationality;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "country_of_residence_id")
private Country countryOfResidence;
#Temporal(TemporalType.DATE)
#Column(name ="date_of_birth")
private Date dateOfBirth = new Date();
#Column(name ="current_job_title")
private String currentJobTitle;
#Column(name = "email_address", nullable = false)
private String emailAddress;
#Column(name = "username")
private String username;
#Column(name ="phone_number")
private String phoneNumber;
#Column(name ="city")
private String city;
#Column(name ="state")
private String state;
#Column(name ="password", nullable = false)
private String password;
#Column(name ="avatar")
private String avatar;
#Column(name ="active", nullable = false)
private Boolean active = true;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_on", updatable = false, nullable = false)
private Date createdOn;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated_on", nullable = false)
private Date updatedOn;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(
name = "member_roles",
joinColumns = #JoinColumn(
name = "member_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "role_id", referencedColumnName = "id")
)
private Set<Role> roles = new HashSet<>();
public void addRole(Role role) {
this.getRoles().add(role);
}
public void clearRoles() {
this.roles = new HashSet<>();
}
}
MemberDto
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public class UpdateMemberDto {
#NotNull(message = "{member.first_name.notNull}")
private String firstName;
#NotNull(message = "{member.last_name.notNull}")
private String lastName;
private Date dateOfBirth;
private String currentJobTitle;
#NotNull(message = "{member.email_address.notNull}")
private String emailAddress;
private String username;
#NotNull(message = "{member.phone_number.notNull}")
private String phoneNumber;
private String city;
private String state;
private String password;
private String avatar;
private Boolean active;
}
ServiceImpl
#Slf4j
#Service
public class UpdateMemberServiceImpl implements UpdateMemberService {
#Autowired
private ModelMapper modelMapper;
private final UpdateMemberRepository repository;
private final MemberJpaRepository jpaRepository;
public UpdateMemberServiceImpl(UpdateMemberRepository repository, MemberJpaRepository jpaRepository) {
this.repository = repository;
this.jpaRepository = jpaRepository;
}
#Override
#Transactional
public Member update(Long id, UpdateMemberDto body) {
Optional<Member> existingMember = jpaRepository.findById(id);
if (existingMember != null) {
Member member = new Member();
member = modelMapper.map(body, Member.class);
member.setId(id);
member = jpaRepository.save(member);
return member;
}
throw new MemberNotFoundException(id);
}
}
Trying to run a delete query on a many-one relationship. But sometime it's stuck for a while when the count of row delete is more then ~50.
Repository:
#Repository
public interface TransitItemRepository extends JpaRepository<TransitItemsMapping, UUID> {
#Modifying
#Transactional
#Query(value="delete from TransitItemsMapping t where t.grouping_form_id=:groupingFormId",nativeQuery = true)
void deleteByGroupingFormId(#Param("groupingFormId") UUID groupingFormId);
}
Domain: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
#JsonManagedReference
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "grouping_form_id")
//#OnDelete(action = OnDeleteAction.CASCADE)
private GroupingForm groupingForm;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(referencedColumnName = "dim_Item_ID",name = "item_id")
private Item item;
#Column(name ="item_relationship_id", insertable = false,updatable = false)
private String itemRelationshipId;
#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;
}
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;
#JsonBackReference
#OneToMany(mappedBy = "groupingForm", cascade = CascadeType.ALL)
private List<ProductItemsMapping> productItems = new ArrayList<>();
#JsonBackReference
#OneToMany(mappedBy = "groupingForm", cascade = CascadeType.ALL)
private List<TransitItemsMapping> transitItems = new ArrayList<>();
#Column(name = "pdf_status")
private String pdfStatus;
public GroupingForm(UUID groupingFormId,String groupingFormName, String vid, String vendorName, String hovbu,
String fid, String factoryName, String status, String sourcingType, Integer totalComments,
Date creationDate, String createdBy, Date modifiedDate, String modifiedBy, String productEngineer,
Integer itemCount, String groupingFormType, String refId, String factoryNameChinese) {
this.groupingFormId = groupingFormId;
this.groupingFormName = groupingFormName;
this.vid = vid;
this.vendorName = vendorName;
this.hovbu = hovbu;
this.fid = fid;
this.factoryName = factoryName;
this.status = status;
this.sourcingType = sourcingType;
this.totalComments = totalComments;
this.creationDate = creationDate!=null?new Timestamp(creationDate.getTime()):null;
this.createdBy = createdBy;
this.modifiedDate = modifiedDate!=null?new Timestamp(modifiedDate.getTime()):null;
this.modifiedBy = modifiedBy;
this.productEngineer = productEngineer;
this.itemCount = itemCount;
this.groupingFormType = groupingFormType;
this.refId = refId;
this.factoryNameChinese = factoryNameChinese;
}
}
Service: methods which already annotated with #Transactional
private void updateTransitItem(GroupingCardsDto groupingCardsDto, GroupingForm groupingForm) {
transitItemRepository.deleteByGroupingFormId(groupingCardsDto.getGroupingFormDto().getGroupingFormId());
groupingFormService.saveTransitItems(groupingCardsDto.getGroupingFormDto(), groupingForm);
}
when I am running eclipse in debug mode then my breakpoint is stuck in delete method. I am using
PostgreSQL 9.6.24 on x86_64-pc-linux-gnu, compiled by Debian clang version 12.0.1, 64-bit
version, and for pool connection Hikari-CP-3.2.0.
And If I let my debug running after long time (~45min) I am getting below error.
marked as broken because of SQLSTATE(08006), ErrorCode(0)\norg.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
Thanks in advance.
There are two possible reasons for this.
Either your delete statement actually takes a really long time, or it is stuck on a lock.
45 min, is certainly a lot for simple delete and could only be expected when you are working on huge amounts of data, like many millions of rows. Use the explain plan to validate that the expected indexes are used.
I consider locks the more likely reason for the problem. You'll need to check what locks are present and where they are coming from. This wiki page about lock monitoring in PostgreSQL seems to be a good starting point.
There are two entity in my project:
1)
public class DonationRegisterMaster extends CommonColumn {
#Column(name = "transaction_no", nullable = false, unique = true)
private String transactionNo;
#Column(name = "transaction_date", nullable = false)
private Date transactionDate;
#Column(name = "donorCode", nullable = false)
private String donorCode;
#Column(name = "program_type")
private String programType;
#Column(name = "currency")
private String currency;
#Column(name = "currency_amount")
private double currencyAmount = 0.0;
#Column(name = "terminal")
private String terminal;
#Column(name = "receive_type")
private String receiveType;
#Column(name = "receiving_bank_account")
private String receivingBankAccount;
#Column(name = "status")
private String status;
#Column(name = "attachment_file_path")
private String attachmentFilePath;
#Column(name = "feature_name")
private String featureName;
#Column(name = "is_submitted", columnDefinition = "boolean default false")
private boolean isSubmitted;
#Column(name = "particulars")
private String particulars;
#Column(name="amount")
private Double amount = 0.0;
#Column(name="rate")
private Double rate = 0.0;
// #JsonManagedReference
// #Transient
#OneToMany(mappedBy = "donationRegisterMaster", fetch = FetchType.LAZY)
// #OneToMany(mappedBy = "donationRegisterMaster", orphanRemoval = true, cascade = {CascadeType.ALL})
List<DonationRegisterDetails> donationRegisterDetailsList;
}
another entity is:
public class DonationRegisterDetails extends CommonColumn {
// #JsonBackReference
#ManyToOne(fetch = FetchType.LAZY)
// #ManyToOne()
#JoinColumn(name = "donation_register_master_id", nullable = false)
private DonationRegisterMaster donationRegisterMaster;
#Column(name = "sl_no")
private Integer slNo;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "chart_of_accounts_id", nullable = false)
private ChartOfAccounts chartOfAccounts;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "project_setup_id", nullable = false)
private ProjectSetup projectSetup;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "area_current_account_code_id")
private AreaCurrentAccountCode areaCurrentAccountCode;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "subsidiary_ledger_id")
private SubsidiaryLedger subsidiaryLedger;
#Column(name = "amount")
private Double amount = 0.0;
#Column(name = "fc_amount")
private Double fcAmount = 0.0;
#Column(name = "remarks")
private String remarks;
// #Transient
#Column(columnDefinition = "boolean default false")
private boolean isDeleted;
}
I have faced this error:
org.hibernate.TransientPropertyValueException: object references an
unsaved transient instance - save the transient instance before
flushing :
com.bracits.financeho.entity.DonationRegisterDetails.donationRegisterMaster
-> com.bracits.financeho.entity.DonationRegisterMaster; nested exception is java.lang.IllegalStateException:
org.hibernate.TransientPropertyValueException: object references an
unsaved transient instance - save the transient instance before
flushing :
com.bracits.financeho.entity.DonationRegisterDetails.donationRegisterMaster.
My JavaCode is:
private DonationRegisterMasterModel updateDonationRegister(DonationRegisterMaster donationRegisterMaster) throws ServiceException {
DonationRegisterMasterModel donationRegisterMasterModel = new DonationRegisterMasterModel();
List<DonationRegisterDetails> totalDonationDetails = new ArrayList<>();
DonationRegisterMasterModel getDonationRegisterMasterModels = new DonationRegisterMasterModel(donationRegisterMaster);
DonationRegisterMasterModel findDonationRegisterMasterModels = new DonationRegisterMasterModel(this.findById(getDonationRegisterMasterModels.getId()));
try {
for (DonationRegisterDetails donationRegisterDetails : donationRegisterMaster.getDonationRegisterDetailsList()) {
if (donationRegisterDetails.getId() == null) {
donationRegisterDetails.setDonationRegisterMaster(donationRegisterMasterService.findById(donationRegisterMaster.getId()));
donationRegisterDetailsService.create(donationRegisterDetails);
totalDonationDetails.add(donationRegisterDetails);
} else {
if (donationRegisterDetails.isDeleted()) {
// Delete & Create
donationRegisterDetailsService.delete(donationRegisterDetails.getId());
} else {
// Update & Create
donationRegisterDetails.setDonationRegisterMaster(new DonationRegisterMaster(findDonationRegisterMasterModels));
donationRegisterDetails.getDonationRegisterMaster();
donationRegisterDetailsService.update(donationRegisterDetails.getId(), donationRegisterDetails);
totalDonationDetails.add(donationRegisterDetails);
}
}
}
if (donationRegisterMaster.getId() == null) {
// donationRegisterMaster = this.create(donationRegisterMaster);
throw new RuntimeException("Donation Master is not found.");
} else {
donationRegisterMaster.setDonationRegisterDetailsList(totalDonationDetails);
donationRegisterMaster = this.update(donationRegisterMaster.getId(), donationRegisterMaster);
}
donationRegisterMasterModel = new DonationRegisterMasterModel(donationRegisterMaster);
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage());
}
return donationRegisterMasterModel;
}
I have tried Cascade.All in entity also. But it is not working. What I have to do solve this problem?
I am getting this error. I am trying to make a search criteria, this search criteria works with other modules I am working on but in this specific module, I am not sure as to why I am encountering this error
(through reference chain: org.springframework.data.domain.PageImpl[\"content\"]->
java.util.Collections$UnmodifiableRandomAccessList[0]->
com.meteor.coral.portfolio.modules.client.domain.Client[\"membershipTypeId\"]->
com.meteor.coral.portfolio.common.infrastructure.codes.domain.CodeValue_$$_jvstb7f_65[\"handler\"])"
This is my Entity class (I just removed some long methods of codes)
I have seen some solutions where they put #JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) but I do not know where exactly should I put it. Help me with this thank you
This is my Client.java class
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.meteor.coral.portfolio.common.infrastructure.codes.data.CodeValueData;
import com.meteor.coral.portfolio.common.infrastructure.codes.domain.CodeValue;
import com.meteor.coral.portfolio.common.infrastructure.core.api.JsonCommand;
import com.meteor.coral.portfolio.common.infrastructure.core.data.ApiParameterError;
import com.meteor.coral.portfolio.common.infrastructure.core.data.DataValidatorBuilder;
import com.meteor.coral.portfolio.common.infrastructure.core.domain.AbstractPersistableCustom;
import com.meteor.coral.portfolio.common.infrastructure.core.exception.PlatformApiDataValidationException;
import com.meteor.coral.portfolio.common.infrastructure.core.service.DateUtils;
import com.meteor.coral.portfolio.common.infrastructure.documentmanagement.domain.Image;
import com.meteor.coral.portfolio.common.infrastructure.security.service.RandomPasswordGenerator;
import com.meteor.coral.portfolio.common.organization.agentreferror.domain.AgentReferror;
import com.meteor.coral.portfolio.common.organization.membershipsubtyperegular.domain.MembershipSubTypeRegular;
import com.meteor.coral.portfolio.common.organization.office.domain.Office;
import com.meteor.coral.portfolio.common.organization.rankandserviceclass.domain.RankAndServiceClass;
import com.meteor.coral.portfolio.common.organization.relationshipandreverse.domain.RelationshipAndReverse;
import com.meteor.coral.portfolio.common.organization.staff.domain.Staff;
import com.meteor.coral.portfolio.common.organization.unitcode.domain.UnitCode;
import com.meteor.coral.portfolio.common.useradministration.domain.AppUser;
import com.meteor.coral.portfolio.modules.client.constants.ClientApiConstants;
import com.meteor.coral.portfolio.modules.group.domain.Group;
import com.meteor.coral.portfolio.modules.paymenttype.domain.PaymentType;
import lombok.Data;
#Entity
#Data
#Table(name = "m_client", uniqueConstraints = { #UniqueConstraint(columnNames = { "account_no" }, name = "account_no_UNIQUE"), //
#UniqueConstraint(columnNames = { "mobile_no" }, name = "mobile_no_UNIQUE") })
//#JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public final class Client extends BaseCoralModel {
//added by Rob
#Column(name = "memberno", length = 20, nullable = true)
private String memberno;
#Column(name = "account_no", length = 20, unique = true, nullable = false)
private String accountNumber;
#ManyToOne
#JoinColumn(name = "office_id", nullable = false)
private Office office;
#ManyToOne
#JoinColumn(name = "transfer_to_office_id", nullable = true)
private Office transferToOffice;
#OneToOne(optional = true)
#JoinColumn(name = "image_id", nullable = true)
private Image image;
/**
* A value from {#link ClientStatus}.
*/
#Column(name = "status_enum", nullable = false)
private Integer status;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "sub_status", nullable = true)
private CodeValue subStatus;
#Column(name = "activation_date", nullable = true)
#Temporal(TemporalType.DATE)
private Date activationDate;
#Column(name = "office_joining_date", nullable = true)
#Temporal(TemporalType.DATE)
private Date officeJoiningDate;
#Column(name = "firstname", length = 50, nullable = true)
private String firstname;
#Column(name = "middlename", length = 50, nullable = true)
private String middlename;
#Column(name = "lastname", length = 50, nullable = true)
private String lastname;
#Column(name = "fullname", length = 100, nullable = true)
private String fullname;
#Column(name = "display_name", length = 100, nullable = false)
private String displayName;
#Column(name = "mobile_no", length = 50, nullable = true, unique = true)
private String mobileNo;
#Column(name = "email_address", length = 50, unique = true)
private String emailAddress;
#Column(name = "is_staff", nullable = false)
private boolean isStaff;
#Column(name = "external_id", length = 100, nullable = true, unique = true)
private String externalId;
#Column(name = "date_of_birth", nullable = true)
#Temporal(TemporalType.DATE)
private Date dateOfBirth;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "gender_cv_id", nullable = true)
private CodeValue gender;
#ManyToOne
#JoinColumn(name = "staff_id")
private Staff staff;
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name = "m_group_client", joinColumns = #JoinColumn(name = "client_id"), inverseJoinColumns = #JoinColumn(name = "group_id"))
private Set<Group> groups;
#Transient
private boolean accountNumberRequiresAutoGeneration = false;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "closure_reason_cv_id", nullable = true)
private CodeValue closureReason;
#Column(name = "closedon_date", nullable = true)
#Temporal(TemporalType.DATE)
private Date closureDate;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "reject_reason_cv_id", nullable = true)
private CodeValue rejectionReason;
#Column(name = "rejectedon_date", nullable = true)
#Temporal(TemporalType.DATE)
private Date rejectionDate;
#ManyToOne(optional = true, fetch=FetchType.LAZY)
#JoinColumn(name = "rejectedon_userid", nullable = true)
private AppUser rejectedBy;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "withdraw_reason_cv_id", nullable = true)
private CodeValue withdrawalReason;
#Column(name = "withdrawn_on_date", nullable = true)
#Temporal(TemporalType.DATE)
private Date withdrawalDate;
#ManyToOne(optional = true, fetch=FetchType.LAZY)
#JoinColumn(name = "withdraw_on_userid", nullable = true)
private AppUser withdrawnBy;
#Column(name = "reactivated_on_date", nullable = true)
#Temporal(TemporalType.DATE)
private Date reactivateDate;
#ManyToOne(optional = true, fetch=FetchType.LAZY)
#JoinColumn(name = "reactivated_on_userid", nullable = true)
private AppUser reactivatedBy;
#ManyToOne(optional = true, fetch=FetchType.LAZY)
#JoinColumn(name = "closedon_userid", nullable = true)
private AppUser closedBy;
#Column(name = "submittedon_date", nullable = true)
#Temporal(TemporalType.DATE)
private Date submittedOnDate;
// #ManyToOne(optional = true, fetch=FetchType.LAZY)
// #JoinColumn(name = "submittedon_userid", nullable = true)
// private AppUser submittedBy;
#Column(name = "updated_on", nullable = true)
#Temporal(TemporalType.DATE)
private Date updatedOnDate;
#ManyToOne(optional = true, fetch=FetchType.LAZY)
#JoinColumn(name = "updated_by", nullable = true)
private AppUser updatedBy;
#ManyToOne(optional = true, fetch=FetchType.LAZY)
#JoinColumn(name = "activatedon_userid", nullable = true)
private AppUser activatedBy;
#Column(name = "default_savings_product", nullable = true)
private Long savingsProductId;
#Column(name = "default_savings_account", nullable = true)
private Long savingsAccountId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "client_type_cv_id", nullable = true)
private CodeValue clientType;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "client_classification_cv_id", nullable = true)
private CodeValue clientClassification;
#Column(name = "legal_form_enum", nullable = true)
private Integer legalForm;
#Column(name = "reopened_on_date", nullable = true)
#Temporal(TemporalType.DATE)
private Date reopenedDate;
#ManyToOne(optional = true, fetch = FetchType.LAZY)
#JoinColumn(name = "reopened_by_userid", nullable = true)
private AppUser reopenedBy;
#Column(name = "proposed_transfer_date", nullable = true)
#Temporal(TemporalType.DATE)
private Date proposedTransferDate;
//***additional fields for membership
//***
//***
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "membership_type_id", nullable = false)
private CodeValue membershipTypeId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "source_place_code_id", nullable = false)
private CodeValue sourcePlaceCodeId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "rank_and_service", nullable = false)
private RankAndServiceClass rankAndService;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "member_status_Id", nullable = false)
private CodeValue memberStatusId;
private String qualifier;
private boolean isChaplain;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "membership_sub_type_id", nullable = false)
private MembershipSubTypeRegular membershipSubTypeId;
private String overrideReason;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "override_by")
private AppUser overrideBy;
private String mothersMaidenName;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "family_group_identifier_id", nullable = false)
private CodeValue familyGroupIdentifierId;
private String badgeNo;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "unit_code", nullable = true)
private UnitCode unitCode;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "employer_id", nullable = true)
private CodeValue employerId;
private String natureOfWork;
private String tin;
#Temporal(TemporalType.DATE)
private Date regularizationDate;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "employment_status_id", nullable = false)
private CodeValue employmentStatusId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "employment_industry_id", nullable = false)
private CodeValue employmentIndustryId;
private String employmentName;
private String employmentPhoneNo;
private String riskRating;
private boolean pep;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "nationality_id", nullable = false)
private CodeValue nationalityId;
private boolean muslim;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "civil_status_id", nullable = false)
private CodeValue civilStatusId;
private String placeOfBirth;
private String phoneNo;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "payment_type_id", nullable = false)
private PaymentType paymentTypeId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "filing_mode_id", nullable = false)
private CodeValue filingMode;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "agent_referror_code_id", nullable = true)
private AgentReferror agentReferrorCodeId;
private boolean psslaiTosri;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "sources_of_funds_wealth_id", nullable = false)
private CodeValue sourcesOfFundsWealthId;
private String memberpan;
private String memberpin;
private String bosEmployeeNo;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "relationship_id", nullable = true)
private RelationshipAndReverse relationshipId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "principal_member")
private Client principalMember;
private boolean mentallyIncapacitated;
}
This is my CodeValue.java class
#Entity
#Table(name = "m_code_value", uniqueConstraints = { #UniqueConstraint(columnNames = { "code_id", "code_value" }, name = "code_value_duplicate") })
public class CodeValue extends AbstractPersistableCustom<Long> {
private static final long serialVersionUID = 5671149962262010193L;
#Column(name = "code_value", length = 100)
private String label;
#Column(name = "order_position")
private int position;
#Column(name = "code_description")
private String description;
#ManyToOne
#JoinColumn(name = "code_id", nullable = false)
private Code code;
#Column(name = "is_active")
private boolean isActive;
#Column(name = "is_mandatory")
private boolean mandatory;
public static CodeValue createNew(final Code code, final String label, final int position, final String description,
final boolean isActive, final boolean mandatory) {
return new CodeValue(code, label, position, description, isActive, mandatory);
}
protected CodeValue() {
//
}
private CodeValue(final Code code, final String label, final int position, final String description,
final boolean isActive, final boolean mandatory) {
this.code = code;
this.label = StringUtils.defaultIfEmpty(label, null);
this.position = position;
this.description = description;
this.isActive = isActive;
this.mandatory = mandatory;
}
public String label() {
return this.label;
}
public int position() {
return this.position;
}
public static CodeValue fromJson(final Code code, final JsonCommand command) {
final String label = command.stringValueOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.NAME.getValue());
Integer position = command.integerValueSansLocaleOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue());
String description = command.stringValueOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.DESCRIPTION.getValue());
Boolean isActiveObj = command.booleanObjectValueOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.IS_ACTIVE.getValue());
boolean isActive = true;
if (isActiveObj != null) {
isActive = isActiveObj;
}
if (position == null) {
position = new Integer(0);
}
Boolean mandatory = command.booleanPrimitiveValueOfParameterNamed(
CODEVALUE_JSON_INPUT_PARAMS.IS_MANDATORY.getValue());
// if the "mandatory" Boolean object is null, then set it to false by default
if (mandatory == null) {
mandatory = false;
}
return new CodeValue(code, label, position.intValue(), description, isActive, mandatory);
}
public Map<String, Object> update(final JsonCommand command) {
final Map<String, Object> actualChanges = new LinkedHashMap<>(2);
final String labelParamName = CODEVALUE_JSON_INPUT_PARAMS.NAME.getValue();
if (command.isChangeInStringParameterNamed(labelParamName, this.label)) {
final String newValue = command.stringValueOfParameterNamed(labelParamName);
actualChanges.put(labelParamName, newValue);
this.label = StringUtils.defaultIfEmpty(newValue, null);
}
final String decriptionParamName = CODEVALUE_JSON_INPUT_PARAMS.DESCRIPTION.getValue();
if (command.isChangeInStringParameterNamed(decriptionParamName, this.description)) {
final String newValue = command.stringValueOfParameterNamed(decriptionParamName);
actualChanges.put(decriptionParamName, newValue);
this.description = StringUtils.defaultIfEmpty(newValue, null);
}
final String positionParamName = CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue();
if (command.isChangeInIntegerSansLocaleParameterNamed(positionParamName, this.position)) {
final Integer newValue = command.integerValueSansLocaleOfParameterNamed(positionParamName);
actualChanges.put(positionParamName, newValue);
this.position = newValue.intValue();
}
final String isActiveParamName = CODEVALUE_JSON_INPUT_PARAMS.IS_ACTIVE.getValue();
if (command.isChangeInBooleanParameterNamed(isActiveParamName, this.isActive)) {
final Boolean newValue = command.booleanPrimitiveValueOfParameterNamed(isActiveParamName);
actualChanges.put(isActiveParamName, newValue);
this.isActive = newValue.booleanValue();
}
return actualChanges;
}
public CodeValueData toData() {
return CodeValueData.instance(getId(), this.label, this.position, this.isActive, this.mandatory);
}
}
This is what I get when I trigger the button
Try to Add #JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) above all entity classes name.
The error shows when parsing the membershipTypeId field, so you can try to add this field to the #JsonIgnoreProperties.
The version for the class Application is getting incremented after the execution of the following statement
Queue queue = queueDao.fetchQueueByApplicationId(application.getApplicationId());
It is a simple fetch query only and it should not increment the version of the call any how. But after above line execution the version is getting incremented unexpectedly for Application class
Could someone please help
Thanks.
Queue.java
#Entity
#Table(name = "queue")
#NamedQuery(name = "queueByApplicationId", query = "SELECT q from Queue q WHERE q.application.applicationId = ?")
public class Queue implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "queue_id", unique = true, nullable = false)
private Long queueId;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created", nullable = false, length = 19)
private Date created;
#Column(name = "created_by")
private Long createdBy;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated", length = 19)
private Date updated;
#Column(name = "updated_by")
private Long updatedBy;
#Version
#Column(name = "version", nullable = false)
private Integer version;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "application_id")
private Application application;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "queue", cascade = { CascadeType.PERSIST, CascadeType.MERGE })
private List<QueueAssignedToRole> queueAssignedToRoles;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "queue", cascade = { CascadeType.PERSIST, CascadeType.MERGE })
private List<QueueAssignedUser> queueAssignedUsers;
getter setter ....
}
Application.java
#Entity
#Table(name = "application")
public class Application implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Long applicationId;
private Integer version;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "application_id", unique = true, nullable = false)
public Long getApplicationId() {
return this.applicationId;
}
public void setApplicationId(Long applicationId) {
this.applicationId = applicationId;
}
#Version
#Column(name = "version", nullable = false)
public Integer getVersion() {
return this.version;
}
public void setVersion(Integer version) {
this.version = version;
}
}
ApplicationQueueDaoImpl.java
#Repository
public class ApplicationQueueDaoImpl extends AbstractDao<Queue> {
private static final Logger LOGGER = LogManager.getLogger(ApplicationQueueDaoImpl.class);
#Override
public Queue fetchQueueByApplicationId(Long applicationId) {
LOGGER.debug("Fetching Queue information for applicationId {}", applicationId);
List<Queue> queues = executeNamedQuery("queueByApplicationId", Queue.class, applicationId);
return CollectionUtils.isEmpty(queues) ? null : queues.get(0);
}
}
AbstractDao.java
protected <T> List<T> executeNamedQuery(String queryName, Class<T> resultType, Object... positionalParams) {
TypedQuery<T> query = entityManager.createNamedQuery(queryName, resultType);
DAOUtils.setPositionalParams(query, positionalParams);
return query.getResultList();
}