I have an oracle db table with columns which are in my FoobarId class.All 3 fields in FooarId are a composite pk in my Foobar table.
I'm inserting data okay on the first run. But when I run it again I'm getting a ORA-00001: unique constraint that my PK is violated. I have similar code in other projects that runs fine. This one seems to not update the record but instead trying to do an insert again. Is there something wrong with my embeddedId?
My entity class:
@Entity
@Table(name = "FOOBAR_TABLE")
public class Foobar implements Serializable {
private static final long serialVersionUID = 4290109857781985996L;
private FoobarId foobarId;
private int containerId;
private String containerType;
private String action;
public Foobar() { }
public Foobar(String itemName, int itemId, Date itemDate) {
foobarId = new FoobarId(itemName, itemId, itemDate);
}
@EmbeddedId
public FoobarId getFoobarId() {
return foobarId;
}
public void setFoobarId(FoobarId foobarId) {
this.foobarId = foobarId;
}
// getters and settters
}
My id class:
@Embeddable
public class FoobarId implements Serializable{
private static final long serialVersionUID = 7393136028821250311L;
private int itemId;
private String itemName;
private Date itemDate;
public FoobarId(){}
public FoobarId(String itemName, int itemId, Date itemDate) {
super();
this.itemId = itemId;
this.itemName = itemName;
this.itemDate = itemDate;
}
// getters/setters
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((itemDate == null) ? 0 : itemDate.hashCode());
result = prime * result + ((itemName == null) ? 0 : itemName.hashCode());
result = prime * result + itemId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
FoobarId other = (FoobarId) obj;
if (itemDate == null) {
if (other.itemDate != null) {
return false;
}
} else if (!itemDate.equals(other.itemDate)) {
return false;
}
if (itemName == null) {
if (other.itemName != null) {
return false;
}
} else if (!itemName.equals(other.itemName)) {
return false;
}
if (itemId != other.itemId) {
return false;
}
return true;
}
}
I have the necessary Repository interface which extends CrudRepository.
In my service class I'm saving a list of Foobar items:
@Transactional
public void addList(List<Activity> itemList) {
logger.info("Saving Activity List size of: " + itemList.size());
activityRepository.save(itemList);
}
create table sql:
CREATE TABLE "FOOBAR"
(
"ITEM_NAME" VARCHAR2(50 CHAR) NOT NULL ENABLE,
"ITEM_ID" NUMBER NOT NULL ENABLE,
"ITEM_DATE" DATE NOT NULL ENABLE,
"CONTAINER_ID" NUMBER,
"CONTAINER_TYPE" VARCHAR2(50 CHAR),
"ACTION" VARCHAR2(50 CHAR),
CONSTRAINT "FOOBAR_PK" PRIMARY KEY ("ITEM_NAME", "ITEM_ID", "ITEM_DATE")
)