JPA composite key one to may relationship separate table - java

I am working on mapping a relationship using a composite key, but the composite key is a separate table.
Car Table
car Id
car description
car Value
SafetyReport Table
safetyReport Id
safetyReport Date
safetyReport Value
CompositeKey CarSafetyReport Table
carid
safetyReportId
One To Many: A car will have many safety reports
JPA:
#Data
#Entity
#Table(name = "CarTable")
public class CarEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "CarId", nullable = false)
private int carId;
#Column(name = "CarDescription", nullable = false)
private String carDescription;
#Column(name = "CarValue", nullable = false)
private String carDescription;
}
#Data
#Entity
#Table(name = "SafetyReport")
public class SafetyReportEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "SafetyReportId", nullable = false)
private int SafetyReportID;
#Column(name = "SafetyReportDate", nullable = false)
private OffsetDataTime date;
#Column(name = "SafetyReportValue", nullable = false)
private String safetyReportValue;
}
#Data
#Entity
#Table(name = "CarSafetyReport")
public class CarSafetyReportEntity implements Serializable {
#EmbeddedId
private CarSafetyReportPk id;
}
#Data
#AllArgsConstructor
#NoArgsConstructor
#Embeddable
public class CarSafetyReportPk implements Serializable {
#Column(name = "CarId", nullable = false)
private int carId;
#Column(name = "SafetyReportId", nullable = false)
private int SafetyReportId;
}
I tried
public class CarEntity {
#OneToMany(mappedBy = "id.carId" )
private List<CarSafetyReportEntity> carSafetyReportEntity;
}
I also tried putting the relationship in the composite key CarSafetyReportPk but i got an error for the annotation #OneToMany in a composite key.

Related

Problems with Hibernate Mapping

I'm having problem with mapping two classes with composite keys.
The first class is Product:
#Entity
#Table(name = "Products")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#SuperBuilder
public class Product {
#EmbeddedId
private ProductKey prodPK;
#Column(name = "name", length = 50, nullable = false)
private String name;
#Column(name = "description", length = 80)
private String description;
#Column(name = "totalStock", columnDefinition = "double(8,2) default 0")
private double totalStock;
#ManyToOne
#JoinColumn(name = "companyId", referencedColumnName = "id", nullable = false)
private Company company;
}
With this #EmbeddedId:
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#EqualsAndHashCode
#Embeddable
public class ProductKey implements Serializable {
#Column(name = "sku", length = 50)
private String sku;
#Embedded
private LotKey lot;
}
At the same time, this embedded class has as part of its composite key another composite key "LotKey"
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#EqualsAndHashCode
#Embeddable
public class LotKey implements Serializable {
#Column(name = "lot")
private String lot;
#ManyToOne
#JoinColumn(name = "company", referencedColumnName = "id")
private Company company;
}
which belongs to the class:
#Entity
#Table(name = "Lots")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#SuperBuilder
public class Lote {
#EmbeddedId
private LotKey lotpk;
#Column(name = "stock")
private double stock;
#Column(name = "expirationDate", columnDefinition = "default current_timestamp()")
private Date expirationDate;
}
But I'm having trouble referencing to them:
#Entity
#Table(name = "quantityProduct")
public class QuantityProduct{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#ManyToOne
#JoinColumns({
#JoinColumn(
name = "sku",
referencedColumnName = "sku"),
#JoinColumn(
name = "lot")
})
private Product product;
#Column(name = "quantity", columnDefinition = "double(8,2) default 0")
private double quantity;
}
I am getting the following error
image
Thank you so much !
In QuantityProduct, set also referencedColumnName in
#JoinColumn(
name = "lot")

how to save entity with relationship in spring boot

I have a spring boot application where I want to send an json object with a relationship. I have one entity called meetingSetting and one called meetingTime. MeetingSetting can have as many meetingTimes as possible and one meetingTime object belongs to one meetingSetting. But when I try to send it I am getting the following error:
not-null property references a null or transient value : com.cbc.coorporateblinddateservice.entities.dates.MeetingTime.meetingsSetting
I tried debugging and noticed that meetingSetting is empty when it is sent inside the times object send in the json. Could someone look at my code and tell me what I am missing, my guess is that I have to extend my saveMethod in meetingSettings but it is just a guess.
here is my MeetingSetting entity:
#Entity
#Table(name = "meeting_settings")
#Data
public class MeetingsSetting {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "meeting_name")
private String meetingName;
#Column(name = "meeting_url")
private String meetingUrl;
#Column(name = "meeting_pw")
private String meetingPw;
#OneToMany(mappedBy = "meetingsSetting", cascade = CascadeType.ALL)
private Set<MeetingTime> meetingTime = new HashSet<>();
}
meetingTime entity:
#Entity
#Table(name = "meeting_times")
#Data
public class MeetingTime {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "meeting_date")
private String date;
#Column(name = "start_time")
private String startTime;
#Column(name = "end_time")
private String endTime;
#ManyToOne()
#JoinColumn(name = "meeting_settings_name", nullable = false)
private MeetingsSetting meetingsSetting;
}
MeetingSettingCOntroller:
#RestController
#RequestMapping("/api/meetingSetting")
public class MeetingSettingController {
#Autowired
MeetingSettingService meetingSettingService;
#PostMapping("/")
public void saveMeeting(#RequestBody MeetingsSetting meetingsSetting){
meetingSettingService.saveMeeting(meetingsSetting);
}
Service:
#Service
public class MeetingSettingService {
#Autowired
MeetingSettingRepository meetingSettingRepository;
public void saveMeeting(#RequestBody MeetingsSetting meetingsSetting){
meetingSettingRepository.save(meetingsSetting);
}
Update new code:
MeetingTime:
#Entity
#Table(name = "meeting_times")
#Data
public class MeetingTime {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "meeting_date")
private String date;
#Column(name = "start_time")
private String startTime;
#Column(name = "end_time")
private String endTime;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "meeting_name", nullable = false)
private MeetingsSetting meetingName;
}
MeetingSettings:
#Entity
#Table(name = "meeting_settings")
#Data
public class MeetingsSetting {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "meeting_name")
private String meetingName;
#Column(name = "meeting_url")
private String meetingUrl;
#Column(name = "meeting_pw")
private String meetingPw;
#OneToMany(mappedBy = "meetingName", cascade = CascadeType.ALL)
private Set<MeetingTime> meetingTime = new HashSet<>();
}
Sql script:
create table meeting_times
(
id bigint auto_increment
primary key,
meeting_date varchar(255) null,
start_time varchar(255) null,
end_time varchar(255) null,
meeting_name varchar(255) null,
constraint fk_meeting_times__meeting_settings_name
foreign key (meeting_name) references meeting_settings (meeting_name)
);
The reason you're getting a null issue is that on #JoinColumn(name = "meeting_settings_name", nullable = false) you've got nullable = false. the column you're joining on is meeting_settings_name which doesn't seem to be a column on meeting_times and the actual name on meeting_settings is meeting_name. You'll have to add meeting_name to meeting_times to create a relation between the two tables to get this to work.

Merging two foreign key columns into EmbeddedID

I have two tables (Product and Supermarket). They have Many to Many relationship so I created an additional table ProductSupermarket. I want the last table to have only one column which is merging the two foreign keys. This is what I have implemented so far but I am stuck with two columns in the ProductSupermarket - product_id and supermarket_id ..
Product
#Entity
#Table(name = "product")
public class Product{
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(name = "product_id")
private Long productID;
..
Supermarket
#Entity
#Table(name = "supermarket")
public class Supermarket{
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(name = "supermarket_id")
private Long supermarketID;
...
ProductSupermarketKey
#Embeddable
public class ProductSupermarketKey implements Serializable {
#Column(name="product_id")
private Long productID;
#Column(name="supermarket_id")
private Long supermarketID;
public ProductSupermarketKey (){}
public ProductSupermarketKey (Long productID, Long supermarketID) {
this.productID = productID;
this.supermarketID = supermarketID;
}
ProductSupermarket
#Entity
#Table(name = "date_event")
public class ProductSupermarket implements Serializable {
#EmbeddedId
private ProductSupermarketKey id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "product_id", insertable = false, updatable = false)
private Product product;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "supermarket_id", insertable = false, updatable = false)
private Supermarket supermarket;

JPA and Hibernate: Entity with composite primary key using multiple #Id

I'm using SpringBoot with JPA and Hibernate.
For a specific entity I need to use a primary key composed by a relationship + a field.
Something like this:
#Entity
#Table(
name = "book",
uniqueConstraints=#UniqueConstraint(columnNames={"book_id",
"field_a"}))
public class Book extends MyBaseEntity {
#Id
#Column(name = "id")
#Type(type = "uuid-char")
private UUID uuid = UUID.randomUUID();
#Column(name = "name", nullable = false)
private String name;
#OneToMany(mappedBy = "book")
private List<Author> authors = new ArrayList<>();
}
#Entity
#Table(name = "author")
#IdClass(CustomID.class)
public class Author extends MyBaseEntity {
/* Here the composite key */
#Id
#ManyToOne()
#JoinColumn(name = "book_id")
private Book book;
#Id
#Column(name = "field_a", nullable = false)
#Type(type = "uuid-char")
private UUID fieldA;
#CreationTimestamp
#Column(name = "creation_date")
private Instant creationDate;
#UpdateTimestamp
#Column(name = "last_mod_date")
private Instant lastModificationDate;
}
public class CustomID implements Serializable {
private UUID book;
private UUID fieldA;
}
Using this approach, after some inserts on the DB, for Author entity book_id column contains values like these:
ÃFË5ÊL©T¾Äd
Why? Why there aren't Book primary keys values?

How to use uniqueConstraint on referenced table column with JPA

How can I include a referenced table column in a unique constraint? I want to create a unique constraint for table Survey for columns toEmail, receipt.receiptSeries and receipt.receiptNum.
See entities below please:
Receipt
#Entity
#Table(name = "RECEIPT")
public class Receipt {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private Long id;
#Column(name = "RECEIPT_SERIES")
private String receiptSeries;
#Column(name = "RECEIPT_NUM")
private String receiptNum;
}
Survey
#Entity
#Table(name = "SURVEY"}
public class Survey {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private Long id;
#ManyToOne(optional = false)
#JoinColumn(name = "RECEIPT_ID")
private Receipt receipt;
#Column(name = "TO_EMAIL")
private String toEmail;
}
I've tried using the approach below with no success:
#Table(name = "SURVEY", uniqueConstraints = {
#UniqueConstraint(columnNames = {"TO_EMAIL", "RECEIPT.RECEIPT_SERIES", "RECEIPT.RECEIPT_NUM"})})
Using a composite primary key with receiptSeries and receiptNum for Receipt is not an option.
Try something like this
#Table(name="notification_status", uniqueConstraints=
arrayOf(UniqueConstraint(columnNames= arrayOf("external_user_id",
"external_organization_id",
"notification_id"))))

Categories

Resources