Hibernate transitive composite foreign key dependency with embedded entity - java

I want to map a existing database (we can't change for now) to Hibernate entities.
But my mapping seems to have a problem with a transitive mapped composite keys I can't overcome.
FluidSampleLabel has FluidSample as foreign key and as part of its own composite primary key. Hibernate seems to ignore the columns/embedded id mapped by the embedded foreign key entity FluidSample in FluidSampleLabel.
Test-Project on Github:
https://github.com/burka/hibernate-transitive-compkey-problem.git
org.hibernate.AnnotationException: A Foreign key refering compkey_problem.model.FluidSample from compkey_problem.model.FluidSampleLabel has the wrong number of column. should be 1
Without #ManyToOne annotated named columns on embedded fks I get the following error:
Caused by: org.hibernate.MappingException: Foreign key (FK246FD874D0837E3B:fluid_sample_label [sample])) must have same number of columns as the referenced primary key (fluid_sample [sampleGroup,pre_post])
create sequence sample_group_seq start 10000;
create table sample_group (
sample_group_id int primary key,
payload varchar(200)
);
create table fluid_sample (
sample_group_id int not null,
pre_post varchar(20) not null check ( pre_post in ( 'PRE', 'POST') ),
amount number(20,10) not null,
primary key ( sample_group_id, pre_post ),
constraint fk_fluid_sample_group foreign key ( sample_group_id ) references sample_group ( sample_group_id )
);
create table fluid_sample_label (
sample_group_id int,
pre_post varchar(20) not null check ( pre_post in ( 'PRE', 'POST') ),
label varchar(200) not null,
primary key ( sample_group_id, pre_post, label ),
constraint fk_fluid_label_fluid foreign key ( sample_group_id, pre_post ) references fluid_sample ( sample_group_id, pre_post )
);
#Entity
#SequenceGenerator(name = "sampleGroupSequence", sequenceName = "sample_group_seq", allocationSize = 1)
#Table(name = "sample_group")
public class SampleGroup
{
#Id
#GeneratedValue(generator = "sampleGroupSequence", strategy = GenerationType.SEQUENCE)
#Column(name = "sample_group_id")
private Integer sampleGroupId;
#OneToMany(mappedBy = "sampleGroup")
private List<FluidSample> fluidSamples = new ArrayList<>();
#Column(name = "payload")
private String payload;
public SampleGroup()
{
}
public FluidSample addNewPreFluidSample()
{
FluidSample sample = new FluidSample(this, PrePost.PRE);
this.fluidSamples.add(sample);
return sample;
}
}
#Entity
#Table(name = "fluid_sample")
public class FluidSample
{
#Id
#ManyToOne
#JoinColumn(name = "sample_group_id")
private SampleGroup sampleGroup;
#Id
#Column(name = "pre_post")
#Enumerated(EnumType.STRING)
private PrePost prePost;
#OneToMany(mappedBy = "sample")
private List<FluidSampleLabel> labels = new ArrayList<>();
#Column(name = "amount")
private BigDecimal amount;
#SuppressWarnings("unused")
private FluidSample()
{
}
public FluidSample(SampleGroup sampleGroup, PrePost prePost)
{
this.sampleGroup = sampleGroup;
this.prePost = prePost;
}
public FluidSampleLabel addNewLabel(String value)
{
FluidSampleLabel label = new FluidSampleLabel(this, value);
this.labels.add(label);
return label;
}
}
#Entity
#Table(name = "fluid_sample_label")
public class FluidSampleLabel
{
#Id
#ManyToOne
#JoinColumns({ #JoinColumn(name = "sample_group_id"), #JoinColumn(name = "pre_post")})
private FluidSample sample;
#Id
private String value;
#SuppressWarnings("unused")
private FluidSampleLabel()
{
}
FluidSampleLabel(FluidSample sample, String value)
{
this.sample = sample;
this.value = value;
}
public String getValue()
{
return this.value;
}
}
public enum PrePost
{
PRE, POST;
}

Related

How can I find an object in JPA by its Composited Key ID

Im trying to find one object from my DB table Real_States which goes like this:
CREATE TABLE REAL_STATES (
address VARCHAR(30) NOT NULL,
admin_id VARCHAR(15) NOT NULL,
resident_id VARCHAR(15),
real_state_type_id INT(6) NOT NULL,
block VARCHAR(3) NOT NULL,
internal_id INT(5) NOT NULL,
PRIMARY KEY (address, block, internal_id),
FOREIGN KEY (real_state_type_id) REFERENCES REAL_STATE_TYPES (real_state_type_id),
FOREIGN KEY (admin_id) REFERENCES ADMINS (admin_id),
FOREIGN KEY (resident_id) REFERENCES RESIDENTS (resident_id)
);
And I want to get a row of this table by its composite Primary Key (address, block, internal_id), all this from my EntityManager. This goes like this:
public RealState findRealState(RealStateID realStateId) {
RealState realState = em.find(RealState.class, realStateId); // first Try, which failed
List<RealState> realStates = em.createQuery("FROM RealState rs WHERE rs.realStateID.address like :" + realStateId.getAddress()).getResultList(); // second try which failed too
for (RealState realState2 : realStates) {
System.out.println(realState2.toString());
}
if (realState == null) {
throw new EntityNotFoundException("Can't find realState for ID " + realStateId.toString());
}
return realState;
}
The RealStateID Class is declared like this:
#Embeddable
public class RealStateID implements Serializable{
private static final long serialVersionUID = 6485406412363395170L;
#Column(name = "address")
private String address;
#Column(name = "block")
private String block;
#Column(name = "internal_id")
private int internal_id;
//getters..setters..
But Im just getting error by error, IDK what I am doing wrong, and I would like to figure out it. Im not using Spring, just JPA Hibernate and Java.
As it's stated in the documentation:
The primary key class must define equals and hashCode methods, consistent with equality for the underlying database types to which the primary key is mapped.
Assuming it, the method:
RealState realState = em.find(RealState.class, new RealStateID(...));
should work as expected.
EDIT Your RealStateID should look like this:
#Embeddable
public class RealStateID implements Serializable{
private static final long serialVersionUID = 6485406412363395170L;
#Column(name = "address")
private String address;
#Column(name = "block")
private String block;
#Column(name = "internal_id")
private int internal_id;`
// getters, setters
#Override
public boolean equals(Object o) {
if ( this == o ) return true;
if ( o == null || getClass() != o.getClass() ) return false;
RealStateID pk = (RealStateID) o;
return Objects.equals(address, pk.address) &&
Objects.equals(block, pk.block) &&
Objects.equals(internal_id, pk.internal_id);
}
#Override
public int hashCode() {
return Objects.hash(address, block, internal_id);
}
}

How to map a OneToOne with ZeroOrOneToOne back reference in JPA?

I have a legacy app which has an entity relationship that looks like this. I changed the names of the fields to less realistic values and reduced to only the relevant fields.
CREATE TABLE `billing_target` (
`billingTargetID` int(11) NOT NULL,
`targetType` char(5) NOT NULL,
`targetID` int(11) NOT NULL
PRIMARY KEY (`billingTargetID`)
);
CREATE TABLE `Client` (
`clientID` int(11) NOT NULL,
`name` varchar(200),
`color` varchar(200),
`shape` varchar(200)
PRIMARY KEY (`clientID`),
CONSTRAINT `fk_client_billingTarget`
FOREIGN KEY (`clientID`)
REFERENCES `billing_target` (`targetID`)
);
My most current attempt which causes an issue when saving as it gives a null entity key exception.
#Data
#Entity
public class BillingTarget implements Serializable {
#Id
#Column(name = "billingTargetID")
private Integer id;
#Column(name = "targetID", nullable = false)
private Integer targetID;
#Column(name = "targetType", nullable = false)
private String type;
}
#Data
#Entity
public class Client implements Serializable {
#Id
#Column(name = "clientID")
private Integer id;
#OneToOne
#JoinColumn(name = "clientID")
#MapsId("targetID")
private BillingTarget billingTarget;
private String name;
private String color;
private String shape;
}
Here's the PlantUML code if interested
#startuml
hide circle
entity BillingTarget {
* billingTargetID <<generated>>
--
* targetType
* targetID <<unique>>
}
entity Client {
* clientID <<fk>>
--
* name
color
shape
}
BillingTarget ||--o| Client : "targetID:clientID"
#enduml
I was already thinking of using a MappedSuperclass but right now it is only one type (though it could be more). Second the billing target may be zero and not null as there's a NOT NULL constraint already present.

Why this Hibernate Relation isn't working?

I try to Connect Pizzas and Ingredients in a n:m relation while all Pizzas have Ingredients as an Attribute List of Ingredients. But in the Relationstable when I create a new Pizza and try to commit there is an Error with the PizzaID in the Relationtable.
The relational Table:
CREATE TABLE `Pizza_Ingredience_Relation` (
`PizzaID` int(11) NOT NULL,
`IngredientID` int(11) NOT NULL,
`Amount` int(11) NOT NULL,
`Volume_Unit` varchar(1) NOT NULL,
PRIMARY KEY (`PizzaID`,`IngredientID`),
KEY `FKc58en2gx5a8n1swmu9tda345` (`IngredientID`),
CONSTRAINT `FK_IngredienceId` FOREIGN KEY (`IngredientID`) REFERENCES `Zutatenliste` (`ID`),
CONSTRAINT `FKc58en2gx5a8n1swmu9tda345` FOREIGN KEY (`IngredientID`) REFERENCES `Zutatenliste` (`ID`),
CONSTRAINT `FKhghfxg8raskdydyu8o8msxtfn` FOREIGN KEY (`PizzaID`) REFERENCES `Pizza` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
The Ingredient Table:
CREATE TABLE `Zutatenliste` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
The Pizza Table:
CREATE TABLE `Pizza` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(20) NOT NULL,
`PreisKlein` double NOT NULL,
`PreisMittel` double NOT NULL,
`PreisGroß` double NOT NULL,
`PreisFamilie` double NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
I have two hibernate Entitites, one is a Pizza Entitiy and one the Ingredient Entitiy:
package Model.PizzenDB.SQLConnectionClasses.MySQL;
import Model.PizzenDB.Pizza;
import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.Where;
import javax.persistence.*;
import java.util.LinkedList;
import java.util.Set;
#Entity
#Table(name = "Pizza")
public class MySQLPizzaHibernateEntity {
#Id
#Column(name = "ID")
private int id;
#Column(name = "Name")
private String name;
#Column(name = "PreisKlein")
private double smallPrice;
#Column(name = "PreisMittel")
private double middlePrice;
#Column(name = "PreisGroß")
private double bigPrice;
#Column(name = "PreisFamilie")
private double familyPrice;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name = "Pizza_Ingredience_Relation",
joinColumns = { #JoinColumn(name = "PizzaID", referencedColumnName = "ID") },
inverseJoinColumns = { #JoinColumn(name = "IngredientID") }
)
private Set<MySQLIngredientWithAmountHibernateEntity> ingredience;
public MySQLPizzaHibernateEntity(String name, double smallPrice, double middlePrice, double bigPrice, double familyPrice) {
this.name = name;
this.smallPrice = smallPrice;
this.middlePrice = middlePrice;
this.bigPrice = bigPrice;
this.familyPrice = familyPrice;
}
public MySQLPizzaHibernateEntity() {
}
}
#Entity
#Table(name = "Zutatenliste")
#SecondaryTable(name = "Pizza_Ingredience_Relation", pkJoinColumns = #PrimaryKeyJoinColumn(name = "IngredientID", referencedColumnName = "ID"))
public class MySQLIngredientWithAmountHibernateEntity {
#Id
#Column(name = "ID")
private int id;
#Column(name = "Name")
private String name;
#Column(table = "Pizza_Ingredience_Relation", name="Amount")
private int amount;
#Column(table = "Pizza_Ingredience_Relation", name = "Volume_Unit")
private char unit;
public MySQLIngredientWithAmountHibernateEntity(String name) {
this.name = name;
}
public MySQLIngredientWithAmountHibernateEntity() {
this("");
}
}
I get the following error message:
20:41:45 [main] [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] ERROR - Field 'PizzaID' doesn't have a default value
20:41:45 [main] [org.hibernate.internal.ExceptionMapperStandardImpl] ERROR - HHH000346: Error during managed flush [org.hibernate.exception.GenericJDBCException: could not execute statement]
I'm not sure what is wrong in detail I guess it has todo with the PizzaID Foreign Key and that it isn't set properly.
For many to many relationship, you are using middle table with extra columns and you need Embeddable key for that which would comprise of Pizza and Ingredient object (names shortened). Something like:
#Embeddable
public class PizzaIngredientPk {
private MySQLPizzaHibernateEntity pizza;
private MySQLIngredientWithAmountHibernateEntity ingredient;
#ManyToOne
public MySQLPizzaHibernateEntity getPizza() {
return pizza;
}
public void setPizza(MySQLPizzaHibernateEntity pizza) {
this.pizza = pizza;
}
#ManyToOne
public MySQLIngredientWithAmountHibernateEntity getIngredient() {
return ingredient;
}
public void setIngredientID(MySQLIngredientWithAmountHibernateEntity ingredient) {
this.ingredient = ingredient;
}
}
Then this would act as Embedded Key in MySQLIngredientWithAmountHibernateEntity as
#EmbeddedId
PizzaIngredientPk pk = new PizzaIngredientPk();
But this won't work with Secondarytable which is used for one-to-one relationship. #SecondaryTable requires mapping to be with a primary key but in this case Embedded ID would become PK. In fact, you have flaw in your design. You are trying to make one side of your many to many relationship as one-to-one.
As per JPA docs There must be only one EmbeddedId annotation and no Id annotation when the EmbeddedId annotation is used.
Try to specify to Hibernate automatically produce primary keys. Put this annotation above your Id fields and re-create your database.
#GeneratedValue(strategy = GenerationType.IDENTITY)
See: https://thoughts-on-java.org/hibernate-tips-use-auto-incremented-column-primary-key/

Many-to-Many Association with Extra Columns

I am not able to map correctly even following all the steps provided in:
https://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/
CREATE TABLE `tb_pla_playlist` (
`id_playlist` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`nm_playlist` VARCHAR(10) NOT NULL,
PRIMARY KEY (`id_playlist`) USING BTREE,
)
CREATE TABLE `tb_mid_midia` (
`id_midia` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`nm_midia` VARCHAR(10) NOT NULL,
PRIMARY KEY (`id_midia`) USING BTREE
)
CREATE TABLE `tb_mip_midia_playlist` (
`id_midia` INT(10) UNSIGNED NOT NULL,
`id_playlist` INT(10) UNSIGNED NOT NULL,
`nr_ordem` INT(10) UNSIGNED NOT NULL,
`CREATED_BY` VARCHAR(10) NOT NULL,
PRIMARY KEY (`id_midia`,`CATEGORY_ID`),
CONSTRAINT `FK_id_midia` FOREIGN KEY (`id_midia`)
REFERENCES `midia` (`id_midia`),
CONSTRAINT `FK_id_playlist` FOREIGN KEY (`id_playlist`)
REFERENCES `playlist` (`id_playlist`)
)
playlist.java
#Entity
#Table(name="tb_pla_playlist")
public class Playlist implements Serializable {
private Set<MidiaPlaylist> midiaPlaylist = new HashSet<MidiaPlaylist>();
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id_playlist")
private Long idPlaylist;
#OneToMany(mappedBy = "id.playlist", cascade = CascadeType.ALL)
private Set<MidiaPlaylist> getMidiaPlaylist(){
return midiaPlaylist;
}
...
}
[erro: In attribute 'midiaPlaylist', the "mapped by" value 'id.playlist' cannot be resolved to an attribute on the target entity.]
midia.java
#Entity
#Table(name="tb_mid_midia")
public class Midia implements Serializable {
private Set<MidiaPlaylist> midiaPlaylist = new HashSet<MidiaPlaylist>();
#Id
#GeneratedValue
#Column(name="id_midia")
private Long idMidia;
#OneToMany(mappedBy = "id.midia", cascade=CascadeType.ALL)
public Set<MidiaPlaylist> getMidiasPlaylist() {
return midiaPlaylist;
}
[erro: In attribute 'midiasPlaylist', the "mapped by" value 'id.midia' cannot be resolved to an attribute on the target entity.]
MidiaPlaylistPK.java
#Embeddable
public class MidiaPlaylistPK implements Serializable {
private Midia midia;
private Playlist playlist;
#ManyToOne(cascade = CascadeType.ALL)
public Midia getMidia(){
return midia;
}
public void setMidia(Midia midia){
this.midia = midia;
}
#ManyToOne(cascade = CascadeType.ALL)
public Playlist getPlaylist(){
return playlist;
}
public void setPlaylist(Playlist playlist){
this.playlist = playlist;
}
}
MidiaPlaylist.java
#Entity
#Table(name="tb_mip_midia_playlist")
#AssociationOverrides({
#AssociationOverride(name="id.playlist", [erro: Persistent type of override attribute "id.playlist" cannot be resolved]
joinColumns = #JoinColumn(name = "id_playlist")),
#AssociationOverride(name="id.midia", [erro: Persistent type of override attribute "id.midia" cannot be resolved]
joinColumns = #JoinColumn(name = "id_midia"))
})
public class MidiaPlaylist implements Serializable {
private MidiaPlaylistPK id = new MidiaPlaylistPK();
private int nrOrdem;
#EmbeddedId [erro: Embedded ID class should not contain relationship mappings]
public MidiaPlaylistPK getId() {
return this.id;
}
#Column(name="nr_ordem", nullable=false)
public int getNrOrdem(){
return this.nrOrdem;
}
#Transient
public Midia getMidia(){
return getId().getMidia();
}
#Transient
public Playlist getPlaylist(){
return getId().getPlaylist();
}
Relational model
Can someone help me with these errors? Ty!
You should remove #ManyToOne anotation in #Embeddable and use #MapId anotation insted of #Transient, there is an example here:
http://www.objectdb.com/api/java/jpa/MapsId

Although there is a Composite Primary Key, Hibernate gives an error when only one key is unique

I'm facing an Hibernate error which says More than one row with the given identifier was found and I'm stuck with it.
I would really appreciate any help on this.
I want to create a table as orderLine that contains product code, quantity .etc for a particular sales order.
A SalesOrder can contain many orderLines.
The composite key for the orderLine table is productCode + OrderNumber. ProductCode is the primary key of the Product table and OrderNumber is the primary key of the SalesOrder table.
In a single SalesOrder there should be only one order line for a particular product.
The composite key is getting generated correctly and I get the following sql statement logged by hibernate.
Hibernate: create table orderLine (orderNumber varchar(255) not null, productCode varchar(255) not null, status varchar(255) not null, quantity integer not null, totalPrice double precision not null, unitPrice double precision not null, primary key (orderNumber, productCode))
When the OrderLine table contains data as below, I Successfully insert a new record to OrderLine table with the OrderNumber ORD001 & ProductCode BIS1003
Immediately after when I try to fetch records from the OrderLine, I'm getting the following error.
Caused by: org.hibernate.HibernateException: More than one row with the given identifier was found: BIS1003, for class: com.salesOrder_ws.entity.OrderLine
Since there is a composite key as the primary, why is hibernate throwing an exception, when only one key of the composite key is not unique?
The Code is below.
OrderLine Entity:
#Entity
#Table(name = "orderLine")
public class OrderLine implements Serializable{
private static final long serialVersionUID = -851110991599534263L;
#AttributeOverrides(value =
{#AttributeOverride(column = #Column(name="productCode"), name = "productCode"),
#AttributeOverride(column = #Column(name="orderNumber"), name = "orderNumber")})
#EmbeddedId
private LineID pk;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "productCode", insertable = false, updatable = false)
private Product product;
private int quantity;
private double unitPrice;
private double totalPrice;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "orderNumber", nullable=false, insertable=false, updatable=false)
private SalesOrder salesOrder;
#Override
public boolean equals(Object obj) {
try {
LineID line = (LineID) obj;
return (this.getSalesOrder().getOrderNumber()
.equals(line.getOrderNumber()) && this.getProduct()
.getCode().equals(line.getProductCode()));
} catch (Exception e) {
return false;
}
}
#Override
public int hashCode() {
return (this.getProduct().getCode() + "" + this.getProduct().getCode()).hashCode();
}
}
SalesOrder Entity
#Entity
#Table(name = "salesOrder")
public class SalesOrder extends BaseEntity{
#Id
private String orderNumber;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "customerCode", nullable = false)
private Customer customer;
private double totalPrice;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "salesOrder", cascade = CascadeType.ALL)
private List<OrderLine> lines;
#Override
public boolean equals(Object obj) {
try {
SalesOrder so = (SalesOrder) obj;
if (this.getOrderNumber().equals(so.getOrderNumber())) {
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
#Override
public int hashCode() {
return this.getOrderNumber().hashCode();
}
}
Embeddable Class
#Embeddable
public class LineID implements Serializable{
private static final long serialVersionUID = -4478828739881744452L;
#Basic(optional = false)
private String productCode;
#Basic(optional = false)
private String orderNumber;
#Override
public boolean equals(Object obj) {
try {
LineID l = (LineID) obj;
return this.productCode.equals(l.getProductCode()) && this.orderNumber.equals(l.getOrderNumber());
} catch (Exception e) {
return false;
}
}
#Override
public int hashCode() {
return (this.getOrderNumber() + "" + this.getProductCode()).hashCode();
}
}
UPDATE
SQL generated by Hibernate :
Hibernate: create table customer (code varchar(255) not null, status varchar(255) not null, address varchar(255), creditLimit double precision not null, currentCredit double precision not null, name varchar(255), phone1 varchar(255), phone2 varchar(255), primary key (code))
Hibernate: create table orderLine (orderNumber varchar(255), productCode varchar(255), status varchar(255) not null, quantity integer not null, totalPrice double precision not null, unitPrice double precision not null, primary key (orderNumber, productCode))
Hibernate: create table product (code varchar(255) not null, status varchar(255) not null, description varchar(255), price double precision not null, quantity integer not null, primary key (code))
Hibernate: create table salesOrder (orderNumber varchar(255) not null, status varchar(255) not null, totalPrice double precision not null, customerCode varchar(255) not null, primary key (orderNumber))
Hibernate: alter table orderLine add constraint UK_9gf3j9l0n1w7d2h4sso3voc77 unique (productCode)
Hibernate: alter table orderLine add index FK_9gf3j9l0n1w7d2h4sso3voc77 (productCode), add constraint FK_9gf3j9l0n1w7d2h4sso3voc77 foreign key (productCode) references product (code)
Hibernate: alter table orderLine add index FK_ojvge4lucwf2gtihxtmnav3u2 (orderNumber), add constraint FK_ojvge4lucwf2gtihxtmnav3u2 foreign key (orderNumber) references salesOrder (orderNumber)
Hibernate: alter table salesOrder add index FK_4lq8ynumala22y9t17ceawo81 (customerCode), add constraint FK_4lq8ynumala22y9t17ceawo81 foreign key (customerCode) references customer (code)
Hibernate: alter table orderLine add constraint UK_9gf3j9l0n1w7d2h4sso3voc77 unique (productCode)
The above SQL is not intended to generate. If I could avoid this unique constraint, the problem will be solved.
Appreciate any help to resolve this issue.
I think you might be missing the #MapsId annotation:
#Entity
#Table(name = "orderLine")
public class OrderLine implements Serializable{
private static final long serialVersionUID = -851110991599534263L;
#AttributeOverrides(value =
{#AttributeOverride(column = #Column(name="productCode"), name = "productCode"),
#AttributeOverride(column = #Column(name="orderNumber"), name = "orderNumber")})
#EmbeddedId
private LineID pk;
#ManyToOne(cascade = CascadeType.ALL)
#MapsId("productCode")
private Product product;
private int quantity;
private double unitPrice;
private double totalPrice;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("orderNumber")
private SalesOrder salesOrder;
#Override
public boolean equals(Object obj) {
try {
LineID line = (LineID) obj;
return (this.getSalesOrder().getOrderNumber()
.equals(line.getOrderNumber()) && this.getProduct()
.getCode().equals(line.getProductCode()));
} catch (Exception e) {
return false;
}
}
#Override
public int hashCode() {
return (this.getProduct().getCode() + "" + this.getProduct().getCode()).hashCode();
}
}

Categories

Resources