We'd like to create unidirectional @OneToOne mapping with foreign key that is not in the master table, but in the slave. By providing following java code, Hibernate tries to find column product_ID in the table product but not in productimage. Is it possible to make it working with the only modifications to annotations?
All unnecessary fields and columns have been stripped from the example.
JPA entities:
@Entity
public class Product {
@Id
@Column(name = "ID", unique = true)
private String id;
// this doesn't work
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "product_ID", nullable = false)
private ProductImage productImage;
// this works, but we want one-to-one
// @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
// @JoinColumn(name = "product_ID", nullable = false)
// private List<ProductImage> productImages;
// getters/setters omitted
}
@Entity
public class ProductImage {
@Id
@Column(name = "ID", unique = true)
private String id;
@Column
@Lob
private Blob data;
// getters/setters omitted
}
Database tables:
CREATE TABLE `product` (
`ID` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
)
CREATE TABLE `productimage` (
`ID` varchar(255) NOT NULL,
`data` longblob NOT NULL,
`product_ID` varchar(255) NOT NULL,
PRIMARY KEY (`ID`),
KEY `FK_123` (`product_ID`),
CONSTRAINT `FK_123` FOREIGN KEY (`product_ID`) REFERENCES `product` (`ID`)
)
@OneToOne is a little misleading. It is most likely different from what you want. Classic database "one to one" relationship is modeled via @ManyToOne JPA annotation in most cases. Try it. Never had a problem with uni-directional relationships via @ManyToOne and @JoinColumn. I'd also explicitly specify productId field in the second class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With