Delete both parent and child in #OneToMany relationship - java

I have an entity called itineraryTraveller, and every itineraryTraveller can have many flightEntity. When I try to delete an itineraryTraveller (parent), from the database, I get this error message:
a foreign key constraint fails (`pquino01db`.`ITINERARYTRAVELLER_FLIGHTENTITY`, CONSTRAINT `FK_ITINERARYTRAVELLER_FLIGHTENTITY_flights_ID` FOREIGN KEY (`flights_ID`) REFERENCES `FLIGHTENTITY` (`ID`))"
Here is my itineraryTraveller entity:
#Entity
public class itineraryTraveller implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<flightEntity> flights;
#Temporal(javax.persistence.TemporalType.DATE)
private Date departureDate;
private String departureLocation;
private String arrivalLocation;
private double cost;
private char status;
private ArrayList<String> stops;
private String stopPrint;
private String userName;
private int iden;
// ...
}
And the flightEntity looks like this:
#Entity
public class flightEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Temporal(javax.persistence.TemporalType.DATE)
private Date departureDate;
private String airlineCode;
private String flightNumber;
private String departureLocation;
private String arrivalLocation;
private double businessCost;
private double economyCost;
private int numBusinessSeats;
private int numEconomySeats;
// ...
}
Can someone see the problem? I think my #OneToMany annotation might be missing something, but I'm not sure what. I want to delete both the parent and child at the same time.

Your relationship between the two entities is unidirectional as there is no mapping from flightEntity back to itineraryTraveller entity as you do not have a #JoinColumn on your flightEntity. There can be one of the following solutions for your problem:
Add a #ManyToOne annotation on the flightEntity as follows:
#Entity
public class flightEntity implements Serializable {
// ....
#ManyToOne
#JoinColumn(name="<name_of_foreignkey_column>")
private itineraryTraveller traveller;
// ...
}
And you have to add a mappedBy attribute to your #OneToMany annotation:
#OneToMany(mappedBy="traveller", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
Thereby making the relationship between the entities bidirectional.
This one can solve the problem if you already have tables in the database with a foreign key relationship.
Use #JoinTable annotation on the #OneToMany annotation:
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
#JoinTable(name="<join_table_name>", joinColumns=#JoinColumn("TRAVELLER_ID"), inverseJoinColumns=#JoinColumn("FLIGHT_ID"))
private List<flightEntity> flights;
(The names of the columns are considered to be examples, and can be changed.)
This last mapping is useful if you don't have tables in the database with foreign key column defined, and it will create a new table as an association between the tables; which is normally the case in a many-to-many relationships.
If it is possible use #ManyToOne annotation on the flights entity. This is normal way of mapping a one-to-many relationships.
Lastly, there are conventions in Java that state class names should begin with a capital letter. So I would rename the entity names to Flight and ItineraryTraveller.

Note that in some cases the #JoinColumn on the child object must have insertable = false and updatable = false like this:
#JoinColumn(name = "user_id", insertable = false, updatable = false)
public class User {
private List<UserRole> roles;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
public List<UserRole> getRoles() {
return this.roles;
}
public void setRoles(List<UserRole> roles) {
this.roles = roles;
}
}
public class UserRole {
#ManyToOne
#JoinColumn(name = "user_id", insertable = false, updatable = false)
private User user;
}

Related

Hibernate inserts null even when field is not null in the object being saved

I am facing a weird issue where even though all fields are set in the java object, when I save the object hibernate tries to insert null values in the fields.
When I further debugged, I saw that while merging the new entity at this line hibernate generates an empty object and sets to the target instead of setting given entity to the target. This results in insert query with null values.
Am I missing some configuration here? Below are the example entities having associations similar to my case.
class Vehicle {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(nullable = false)
#Enumerated(EnumType.STRING)
#EqualsAndHashCode.Include
private VehicleType vehicleType;
#OneToOne(mappedBy="vehicle", fetch=FetchType.LAZY)
private Car car;
#OneToOne(mappedBy="vehicle", fetch=FetchType.LAZY)
private Truck truck;
}
class Car {
#Id
private Integer id;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#MapsId
#JoinColumn(name = "vehicle_id")
private Vehicle vehicle;
...
}
class Truck {
#Id
private Integer id;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#MapsId
#JoinColumn(name = "vehicle_id")
private Vehicle vehicle;
...
}
I encountered the same problem, in my case I have an application with:
public class Claim extends BaseEntity<Integer> implements Serializable {
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "claimdetailsid", referencedColumnName = "id")
private ClaimDetails claimDetails;
#OneToOne(cascade = CascadeType.PERSIST)
#JoinColumn(name = "beneficiaryid", referencedColumnName = "id")
private Beneficiary beneficiary;
....
}
When I saved the Claim entity, the Claim and ClaimDetails objects were inserted correctly. The other entities had all the fields null, except the id and the creation date.
I tried changing CascadeType.PERSIST to CascadeType.ALL, that solved my insert problem.
But the delete cascade doesn't work now.

Automatically delete child entity using orphanRemoval Spring JPA

Currently I have the following 2 entities with a one to many relationship -
#Data
#Entity
#Table(name = "invoice_line")
#IdClass(InvoiceLinePK.class)
public class InvoiceLineEntity {
#Id
#Column(name = "line_id")
private String lineId;
#Id
#Column(name = "client_id")
private Integer clientId;
#Id
#Column(name = "invoice_id")
private String invoiceId;
#Column(name = "item_id")
private String itemId;
#Column(name = "amount")
private BigDecimal amount;
#ManyToOne
private InvoiceEntity invoice;
}
#Entity
#Table(name = "invoice")
#IdClass(InvoicePK.class)
#Data
public class InvoiceEntity {
#Id
#Column(name = "client_id")
private Integer clientId;
#Id
#Column(name = "invoice_id")
private String invoiceId;
#Column(name = "description")
private String description;
#Column(name = "txn_total_amount")
private BigDecimal txnTotalAmount;
#Column(name = "created_time", updatable = false)
#CreationTimestamp
private Date createdTime;
#Column(name = "updated_time")
#UpdateTimestamp
private Date updatedTime;
#OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "invoice")
private List<InvoiceLineEntity> invoiceLines;
}
In a case wherein let's say, one of my existing invoice has 3 lines and I receive a request that this particular invoice has been updated and it now has only 1 line instead of the previous 3 (so the other 2 have to be deleted), I would like to create a new Invoice object with this 1 InvoiceLineEntity and then do a invoiceRepository.save(invoice)
I am expecting that the other 2 InvoiceLine records would be automatically deleted because the orphanRemoval flag is enabled.
Can someone tell me how I can achieve this relationship by tweaking the entity relationship structure of the above 2 entities?
Your child entity must be the owner of the relationship, so that the orphans are allowed to be deleted
If you change and add mappedBy to that relation
#OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "bill")
private List<BillLine> billLines;
Then the BillLine must also hold a reference
public class BillLine {
#Id
#Column(name = "line_id")
private String lineId;
#Id
#Column(name = "company_id")
private Integer companyId;
#Id
#Column(name = "bill_id")
private String billId;
#Column(name = "item_id")
private String itemId;
#Column(name = "amount")
private BigDecimal amount;
#ManyToOne
private Bill bill;
}
Now it will remove the orphans
Also since you have multiple #Id on each entity. Do you know that you have to either declare a composite class or an embeddable class? Without one of those the multiple Ids are not valid.
Edit:
1) My bad mappedBy should be placed inside #OneToMany and not #JoinColumn. I have corrected it in my answer
2) Remove #JoinColumn. It is wrong in your configuration. By default #OneToMany inserts a column in the side of the #ManyToOne which holds the references to the primary table. You can override those default configurations and create a separate table for mappings but then you need the #JoinTable and I don't see any reason for that here.
This here
#JoinColumns(value = { #JoinColumn(name = "company_id", referencedColumnName = "company_id"),
#JoinColumn(name = "bill_id", referencedColumnName = "bill_id") })
definitely does not belong on #OneToMany
The following can be applied to #OneToMany but as said before I don't see any reason to do that and complicate a simple mapping which does not require a separate table.
#JoinTable(joinColumns = #JoinColumn(name = "company_id", referencedColumnName = "company_id"),
inverseJoinColumns = #JoinColumn(name = "bill_id", referencedColumnName = "bill_id") )
Check here for more information Jpa primary key

ManyToOne not persisted

#OneToMany side of the relation populates well but the #ManyToOne side overrides each time(only the last item persists)
#Entity
#Table(name="order")
public class Order {
#Id
#Column(name ="orderId")
private String orderId;
#OneToMany(targetEntity = Items.class,
fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "orderId")
#NotNull
private Set<Items> items;
.......
}
#Entity
public class Items {
#Id
private String itemId;
#ManyToOne
#JoinColumn(name="orderId",referencedColumnName = "orderId")
private Order order;
............
}
#Entity
#Table(name="order")
public class Order {
#Id
#Column(name ="orderId")
private String orderId;
#OneToMany(targetEntity = Items.class,
fetch = FetchType.EAGER, cascade = CascadeType.ALL
,mappedBy = "item_id")
#NotNull
private Set<Items> items;
.......
}
#Entity
public class Items {
#Id
private String itemId;
#ManyToOne
#JoinColumn(name="orderId",referencedColumnName = "orderId")
private Order order;
............
Replace targetEntity = Items.class by mappedBy = "order"
and remove referencedColumnName = "orderId" and #JoinColumn(name = "orderId") from OneToMany.
Also if you really need eager fetching delete it from OneToMany side - ManyToOne is eager by default.

How to build one to many relationship with different entities which have a composite key with Hibernate, JPA?

I want to build entity classes for the following relationship. I want an entity ProductWiseCustomer which has a composite key. Those key also mapped with Product and Customer entities. How to achieve the purpose?
So far what I have done.
Product.java
#Entity
#Table(name = "product")
public class Product {
#Id
private Long productId;
private String productName;
private Decimal productPrice;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = CustomerProductCompound.class)
private Set<CustomerProductCompound> customerProductCompound;
//Constructor
//Setter-getter
}
Customer.java
#Entity
#Table(name = "customerinfo")
public class CustomerInfo {
#Id
private Long customerId;
private String customerName;
private Boolean isActive;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = CustomerProductCompound.class)
private Set<CustomerProductCompound> customerProductCompound;
//Constructor
//Setter-getter
}
CustomerProductCompound.java
#Embeddable
public class CustomerProductCompound
{
#ManyToOne
#JoinColumn(name = "customerId")
private CustomerInfo customerInfo;
#ManyToOne
#JoinColumn(name = "productId")
private Product product;
//Constructor
//Setter-getter
}
While running the application getting the following error:
Use of #OneToMany or #ManyToMany targeting an unmapped class: com.auth.model.CustomerInfo.customerProductCompound[com.auth.model.CustomerProductCompound].
One solution is to use a composite identifier with #EmbeddableId.
#Entity
public class ProductWiseCustomer {
#EmbeddedId
private ProductCustomerKey key;
}
#Embeddable
public class ProductCustomerKey {
#ManyToOne(fetch = FetchType.LAZY)
private Customer customer;
#ManyToOne(fetch = FetchType.LAZY)
private Product product;
}
Please see the hibernate documentation:
https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#identifiers-composite-aggregated
CustomerProductCompound as you have defined just the primary key of ProductWiseCustomer. Your collections inside CustomerInfo and Product must contain ProductWiseCustomer items, not its key.
#Entity
#Table(name = "product")
public class Product {
#Id
private Long productId;
private String productName;
private Decimal productPrice;
#OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<ProductWiseCustomer> productWiseCustomers;
}
#Entity
#Table(name = "customerinfo")
public class CustomerInfo {
#Id
private Long customerId;
private String customerName;
private Boolean isActive;
#OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<ProductWiseCustomer> productWiseCustomers;
}
Notice I added the mappedBy property in the annotations. It needs to point to the property name on the other side that refers to this object. The JPA name, not the SQL name. targetEntity is rarely necessary, and I've suggested orphanRemoval, so that if you remove one from the set, you don't have to manually delete it for it to go away.
As for the ProductWiseCustomer, you do need the same key as shown by Modular Coder
#Embeddable
public class ProductCustomerKey {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "customerId)
private Customer customer;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "productId")
private Product product;
}
But I recommend you use #IdClass instead of #EmbeddedId
#Entity
#IdClass(ProductCustomerKey.class)
public class ProductWiseCustomer {
#ManyToOne(fetch = FetchType.LAZY) // should be lazy here
#JoinColumn(name = "customerId)
private Customer customer;
#ManyToOne(fetch = FetchType.LAZY) // should be lazy here
#JoinColumn(name = "productId")
private Product product;
private OffsetDateTime createDate;
private String remarks;
// getters, setters
}

OneToMany with #EmbeddedId and kundera

I have two class and I want to use OneToMany relation with EmbeddedId
(Im working with kundera framework)
my sensor entity class:
public class SensorEntitie implements Serializable {
#EmbeddedId
private CompoundKey key;
#Column
private float temperature;
#Column
private float pressure;
#OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
#JoinColumn(name="what I should to put here")
private List<PieceEntitie> pieces;
}
#Embeddable
public class CompoundKey
{
#Column
private String IdSensor;
#Column
private long date;
#Column(name = "event_time")
private long eventTime;
my piece class entity
public class PieceEntitie implements Serializable{
/**
*
*/
#Id
private String IdPiece;
#Column
private double width;
#Column
private double height;
#Column
private double depth;
but how can i fill the blank in #JoinColumn
I found the solution :
to use OneToMany relation with EmbeddedId, I should to declare JoinColumns and multiple of JoinColumn
#OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
#JoinColumns({
#JoinColumn(name = "idsensor", referencedColumnName = "idsensor"),
#JoinColumn(name = "date", referencedColumnName = "date"),
#JoinColumn(name = "event_time", referencedColumnName = "event_time")
})
You need to do some following steps for fixing problem
Remove #JoinColumn you dont need to write that statement
Remove #OneToMany to created object
Bind #OneToMany with getter method as per my following code
#OneToMany(mappedBy = "pieceEntitie", cascade = CascadeType.ALL,
fetch=FetchType.EAGER)
public Set<PieceEntitie> getPieceEntitie() {
return pieceEntitie;
}

Categories

Resources