Can not find entity of the oneToOne relation - spring-boot

public class Maintenance implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "maintenance_issue_mod",
joinColumns = #JoinColumn(name = "maintenance_id"),
inverseJoinColumns = #JoinColumn(name = "issue_mod_id"))
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<IssueMod> issueMod = new HashSet<>();
#OneToOne(fetch = FetchType.LAZY, targetEntity = COrder.class)
#NotNull
#NotFound(
action = NotFoundAction.IGNORE)
#JoinColumn(name="c_order_id", nullable = false, insertable = false,
updatable = false)
private COrder cOrder;
#OneToOne
#JoinColumn(name = "invoice_id")
private Invoice invoice;
#OneToOne
#JoinColumn(name = "referred_invoice_id")
private Invoice referredInvoice;
getter and setter
this is the Maintenance class and relation of the Maintenance and COrder is OneToOne .
this is corder class
public class COrder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#CreatedDate
#NotNull
#Column(name = "created", nullable = false)
private Instant created = Instant.now();
#Size(max = 255)
#NotNull
#Column(name = "order_number", length = 255, nullable = false, unique = true)
private String orderNumber;
Maintenance maintenance = maintenanceRepository.findById(maintenanceInvoiceDTO.getMaintenanceId());
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> " +maintenance);
COrder currentOrder = cOrderRepository.findOneById(maintenance.getcOrder().getId());
in the service to find the maintenance through the maintenanceId
then we get the following error
'Unable to find in.bsrnetwork.ctrack.domain.COrder with id 1'
but the corder id 1 is present in the the corder table

Related

Spring Data persisting Phantom Child with Null value - not null property references a null or transient value

I have the following Entities in my Project:
#Getter
#Setter
#Entity
#Table(uniqueConstraints = #UniqueConstraint(columnNames = { "purchaseId" }))
public class Purchase {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long purchaseId;
#Column(unique = true, nullable = false, length = 15)
private String purchaseNo;
#Column(nullable = false, length = 15)
private String batchCode;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "supplier.supplierId", foreignKey = #ForeignKey(name = "FK_purchase_supplier"), nullable = false)
private Supplier supplier;
#Column(nullable = false)
private LocalDate purchaseDate;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "purchaseId", nullable = false)
private List<PurchaseItem> purchaseItems;
private Double totalAmount;
#ManyToOne
#JoinColumn(name = "userId", nullable = false, foreignKey = #ForeignKey(name = "FK_invoice_purchases"))
private User staff;
#Column(length = 100)
private String remarks;
#Column(nullable = false, updatable = false)
#CreationTimestamp
private LocalDateTime createdAt;
private boolean isDeleted = false;
}
#Getter
#Setter
#Entity
#Table(uniqueConstraints = #UniqueConstraint(columnNames = {"purchaseItemId"}))
public class PurchaseItem {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long purchaseItemId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "purchaseId", insertable = false, updatable = false, foreignKey = #ForeignKey(name="FK_purchase_item"))
private Purchase purchase;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "productId", foreignKey = #ForeignKey(name="FK_product_item"), nullable = false)
private Product product;
private Double itemAmount;
#Column(nullable = false)
private Double quantity;
private Double itemTotalAmount;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
#PrimaryKeyJoinColumn(foreignKey = #ForeignKey(name = "FK_purchacase_item_batch"))
private PurchaseProductBatch productPurchaseBatch;
public void setPurchaseProductBatch() {
PurchaseProductBatch productPurchaseBatch = new PurchaseProductBatch();
productPurchaseBatch.setProduct(this.product);
productPurchaseBatch.setQuantity(this.quantity);
productPurchaseBatch.setPurchaseItem(this);
this.productPurchaseBatch = productPurchaseBatch;
}
}
#Getter
#Setter
#Entity
#Table()
public class PurchaseProductBatch{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long productBatchId;
#ManyToOne(cascade = CascadeType.DETACH)
#JoinColumn(name = "productId", foreignKey = #ForeignKey(name = "FK_product_purch"))
private Product product;
private Double quantity;
#OneToOne(fetch = FetchType.EAGER)
#MapsId
private PurchaseItem purchaseItem;
private boolean isDeleted = false;
#OneToMany(cascade = CascadeType.PERSIST)
#JoinColumn(name = "productBatchId", foreignKey = #ForeignKey(name = "FK_purchase_batch_qty"))
private Set<InvoicePurchaseBatchQuantity> invoicePurchaseBatchQuantities;
}
During Purchase Insert, everything works fine. However, if I update the Purchase record in the database and add new PurchaseItem entry, I encounter the issue below:
org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : com.be.entity.PurchaseItem.product; nested
I have debugged my application and I see that there is a Product instance inside all of the PurchaseItem. When I commented out the PurchaseProductBatch inside PurchaseItem, everything works fine so I conclude that it is the causing the issue. However, I don't understand how and why JPA seems to create phantom PurchaseItem Records with no value.
Also, if I only update an existing PurchaseItem entry in Purchase, I don't encounter any issues.

Why am i getting an infinite list with stack overflow?

Im making an bungalow reservation system but i cant get a list with an many to many relationship i keep getting an infinite list with stackoverflow error.
This worked find but happens when i added the many to many relationship.
Attraction Entity this contains a many to many relationship with
the visit entity
#Entity
#Table(name = "attraction")
public class Attraction {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name")
private String name;
#Column(name = "historical")
private Boolean historical;
#Column(name = "religious")
private Boolean religious;
#Column(name = "beaches")
private Boolean beaches;
#Column(name = "animal_sanc")
private Boolean animalSanc;
#Column(name = "hiking")
private Boolean hiking;
#Column(name = "forest")
private Boolean forest;
#Column(name = "parks")
private Boolean parks;
#Column(name = "lakes")
private Boolean lakes;
#ManyToOne
#JoinColumn(name = "bungalow_id")
private Bungalow bungalow;
#ManyToMany(cascade = {CascadeType.MERGE,CascadeType.REFRESH})
#JoinTable(
name = "visit_has_attraction",
joinColumns = #JoinColumn(name = "attraction_id"),
inverseJoinColumns = #JoinColumn(name = "visit_id")
)
private List<Visit> visitList;
//Constructer, Getters and Setters
}
Visit entity
This is the other end of the many to many relationship
#Entity
#Table(name = "visit")
public class Visit {
#Id
#Column(name = "id")
private int id;
#Column(name = "date")
private Date date;
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#ManyToMany(cascade = {CascadeType.MERGE,CascadeType.REFRESH})
#JoinTable(
name = "visit_has_attraction",
joinColumns = #JoinColumn(name = "visit_id"),
inverseJoinColumns = #JoinColumn(name = "attraction_id")
)
List<Attraction> attractions;
//Constructer, Getters and Setters
}
JPA Repository
public List<Attraction> findAttractionsByVisitList(Visit visit);
ER of the app
1
I added #JsonIgnore to one of the sides in many to many relationships and added #JsonBackReference to ManyToOne side and #JsonManagedReference to OneToMany side of all the one to many relationships.
#Entity
#Table(name = "attraction")
public class Attraction {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name")
private String name;
#Column(name = "historical")
private Boolean historical;
#Column(name = "religious")
private Boolean religious;
#Column(name = "beaches")
private Boolean beaches;
#Column(name = "animal_sanc")
private Boolean animalSanc;
#Column(name = "hiking")
private Boolean hiking;
#Column(name = "forest")
private Boolean forest;
#Column(name = "parks")
private Boolean parks;
#Column(name = "lakes")
private Boolean lakes;
#ManyToOne
#JoinColumn(name = "bungalow_id")
#JsonBackReference
private Bungalow bungalow;
#ManyToMany(cascade = {CascadeType.MERGE,CascadeType.REFRESH})
#JoinTable(
name = "visit_has_attraction",
joinColumns = #JoinColumn(name = "attraction_id"),
inverseJoinColumns = #JoinColumn(name = "visit_id")
)
#JsonIgnore
private List<Visit> visitList;
//Constructer, Getters and Setters
}
Visit entity
This is the other end of the many to many relationship
#Entity
#Table(name = "visit")
public class Visit {
#Id
#Column(name = "id")
private int id;
#Column(name = "date")
private Date date;
#ManyToOne
#JoinColumn(name = "user_id")
#JsonBackReference
private User user;
#ManyToMany(cascade = {CascadeType.MERGE,CascadeType.REFRESH})
#JoinTable(
name = "visit_has_attraction",
joinColumns = #JoinColumn(name = "visit_id"),
inverseJoinColumns = #JoinColumn(name = "attraction_id")
)
List<Attraction> attractions;
//Constructer, Getters and Setters
}

Could not write JSON: Infinite recursion

I am getting StackOverflow recursion error when I run query in Postman or Browser .
When i run says:
.w.s.m.s.DefaultHandlerExceptionResolver : Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError)
Here is the model classes :
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String title;
#NotNull
private String description;
#NotNull
private double price;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "category_id", nullable = false)
private Category category;
private boolean isSealed;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "currency_id", nullable = false)
private Currency currency;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "user_id", nullable = false)
private User user;
#Nullable
#OneToMany(mappedBy = "product",
cascade = CascadeType.ALL, orphanRemoval = true)
private List<Images> images;
private Date createdDate = new Date();
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "product")
private View view;
#OneToOne(fetch = FetchType.LAZY,cascade=CascadeType.ALL)
#JoinColumn(name="type_id")
private Type type;
private Long viewCount; }
#Entity public class Images{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String imagePath;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "product_id")
private Product product; }
#Entity public class User implements UserDetails, Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotEmpty
private String fullName;
#NotEmpty
#Email
#Column(unique = true)
private String email;
#NotNull
#Column(unique = true)
private int phoneNumber;
#NotEmpty
#Size(min = 5)
private String password;
private Date createAt = new Date();
#Nullable
private String picPath;
#Nullable
private String token;
#ManyToMany
#JoinTable(name = "user_roles", joinColumns = {#JoinColumn(
name = "user_id")},
inverseJoinColumns = {#JoinColumn(name = "role_id")})
private List<Role> roles;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "user")
private Product product;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "user")
private View view; }
#Entity
public class Currency{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String code;
private String currency;
private String region_country;
#OneToOne(mappedBy = "currency", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Product product; }
#Entity
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String imagePath;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY,
mappedBy = "category")
private Product product;
#OneToMany(mappedBy = "category", fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private Set<Brand> brands; }
#Entity public class Brand {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "category_id", nullable = false)
private Category category; }
#Entity public class View {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "user_id", nullable = false)
private User user;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "product_id", nullable = false)
private Product product; }
#Entity public class Type {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String name;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "type")
private Product product; }
#Id
private String role;
#ManyToMany(mappedBy = "roles")
private List<User> users;
}
More than one of your entities have each other in themselves.
For example, Product has an object of User, and User has an object of Product.
To solve this, you have to write
#JsonBackReference(value = "user-product")
private User user;
in the Product class,
and
#JsonManagedReference(value = "user-product")
private Product product;
In the user class.
Do it in every field and for every class that call each other.
Also, Check this out
JPA: Having lists on both ends without infinite loop
You have cycles in your data model. For example, Product holds Images and Images point back to Products.
This works in an object oriented world, because only pointer references are stored in those fields.
When serialized, however, the actual object is written out as json text. Your Product prints the Images object which in turn prints the Product object which again prints the Image object and so on.
You need to decide how you want to represent your json, map your database model into simple plain old java object and use this for serializations. These POJOs are often called View Model or Transport Objects.

How to fix Error ManyToMany in #RestController?

I'm an entity Story:
#Entity
#Table(name = "story", schema = "")
#Data
public class Story implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "sID", unique = true, nullable = false)
private Long sID;
#Column(name = "vnName", nullable = false)
private String vnName;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "_scategory",
joinColumns = {#JoinColumn(name = "sID", nullable = false)},
inverseJoinColumns = {#JoinColumn(name = "cID", nullable = false)})
private List<Category> categoryList;
}
And Entity Category:
#Entity
#Table(name = "category", schema = "", uniqueConstraints = {#UniqueConstraint(columnNames = {"cMetatitle"}),
#UniqueConstraint(columnNames = {"cName"})})
#Data
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "cID", unique = true, nullable = false)
private Integer cID;
#Column(name = "cName", unique = true, nullable = false, length = 150)
private String cName;
#ManyToMany(mappedBy = "categoryList")
private List<Story> storyList;
}
But when I grab the Story in RestController, I get the following error message:
WARN http-nio-8080-exec-9
o.s.w.s.m.s.DefaultHandlerExceptionResolver:234 - Failure while trying
to resolve exception
[org.springframework.http.converter.HttpMessageNotWritableException]
java.lang.IllegalStateException: Cannot call sendError() after the
response has been committed
Can anybody show me how to fix it? Thank you!

Spring JpaRepository manyToMany bidirectional should save instead of update

if got a language table and a system table with a many-to-many relationship:
Language:
#JsonAutoDetect
#Entity
#Table(name = "language")
public class Language implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "language_id", nullable = false)
private int languageId;
#Column(name = "language_name", nullable = false)
private String languageName;
#Column(name = "language_isocode", nullable = false)
private String languageIsoCode;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "system_language", joinColumns = {#JoinColumn(name = "language_id", updatable = false)},
inverseJoinColumns = {
#JoinColumn(name = "system_id", updatable = false)}, uniqueConstraints = {
#UniqueConstraint(columnNames = {
"language_id",
"system_id"
})})
private List<System> systems;
public Language() {
}
// GETTER & SETTERS
// ....
}
System
#JsonAutoDetect
#Entity
#Table(name = "system")
public class System implements Serializable {
#Id
#Column(name = "system_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer systemId;
#Column(name = "system_name", nullable = false, unique = true)
private String systemName;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "university_id", nullable = false)
private University university;
#JoinColumn(name = "calender_id", nullable = false)
#OneToOne(fetch = FetchType.EAGER)
private Calendar calender;
#OneToMany(mappedBy = "system")
#LazyCollection(LazyCollectionOption.FALSE)
private List<SystemUserRole> systemUserRoleList;
#OneToMany(mappedBy = "system")
#LazyCollection(LazyCollectionOption.FALSE)
private List<Role> roleList;
#OneToOne(mappedBy = "system")
#LazyCollection(LazyCollectionOption.FALSE)
private CsmUserEntity csmUserEntity;
#ManyToMany(mappedBy = "systems")
#LazyCollection(LazyCollectionOption.FALSE)
private List<Language> languages;
public System() {
}
// GETTER & SETTERS
// ....
}
When im writing a first dataset (systemId=1, language_id=20) into the table, everything works fine. But when i try to write a second dataset with the same language_id but with other system_id (systemId=2, language_id=20), then the existing dataset gets updated. But i want to have a new dataset instead. What can i do?
Thanks in advance!

Resources