Hi all,
is it possible to create relations in hibernate / jpa that are fetched when the containing entity is fetched but will never ever result in any db updates, when the containing entity is saved? I'll try to make the requirement clear by an example.
I have a simple entity B
@Entity
public class B {
private int bId;
@Id
public int getBId() {
return bId;
}
public void setBId(int aId) {
bId = aId;
}
}
And another entity A, which contains a uni-directional many-to-many mapping to this class.
@Entity
public class A {
private int aId;
private List<B> bs;
@Id
public int getAId() {
return aId;
}
public void setAId(int aId) {
this.aId = aId;
}
@ManyToMany
@JoinTable(name = "A_B",
joinColumns = {@JoinColumn(name = "AID")},
inverseJoinColumns = {@JoinColumn(name = "BID")}
)
public List<B> getBs() {
return bs;
}
public void setBs(List<B> aBs) {
bs = aBs;
}
}
When entity A is fetched from db and merged afterwards as follows
A a = em.find(A.class, 1);
a.getBs().size();
em.merge(a);
, the merge results in the following SQL statements
Hibernate:
delete
from
A_B
where
AID=?
Hibernate:
insert
into
A_B
(AID, BID)
values
(?, ?)
Hibernate:
insert
into
A_B
(AID, BID)
values
(?, ?)
I have to avoid these deletes + updates. For my application I can ensure that the mapping table will never ever be updated using hibernate. Anyway, it is required to update the containing entity.
So my question is: Is it possible to map such "read-only" collections and to avoid db changes?
Best regards
Thomas
Update:
These are the tables and the data I'm using:
CREATE TABLE A (
AID INTEGER NOT NULL
)
DATA CAPTURE NONE ;
CREATE TABLE B (
BID INTEGER NOT NULL
)
DATA CAPTURE NONE ;
CREATE TABLE A_B (
AID INTEGER NOT NULL,
BID INTEGER NOT NULL
)
DATA CAPTURE NONE ;
INSERT INTO A (AID) VALUES (1);
INSERT INTO B (BID) VALUES (1);
INSERT INTO B (BID) VALUES (2);
INSERT INTO A_B (AID, BID) VALUES (1, 1);
INSERT INTO A_B (AID, BID) VALUES (1, 2);
In addition the collection also needs to be initialized before the merge is performed:
a.getBs().size();
Note: I've added the line from above to the original post, too.