I have two entities that have a relation OneToOne, like this:
#Entity
#Table(name = "FOO")
Foo{
#OneToOne(fetch = FetchType.LAZY, mappedBy = "foo")
#Cascade({org.hibernate.annotations.CascadeType.ALL})
#JoinColumn(name = "BAR_ID")
private Bar bar;
// getters and setters
}
#Entity
#Configurable
#Table(name = "BAR")
Bar{
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "FOO_ID")
#Cascade({org.hibernate.annotations.CascadeType.ALL})
private Foo foo;
// getters and setters
}
In the Service layer, I make the connection by setting Bar in Foo:
Bar.setFoo(foo);
barDAO.saveOrUpdate(bar);
Wich saves the foo id in the Bar table. But the opposite doesn't happen. Is it possible for hibernate to save both ids making only one set? I thought this would be working already
You need to understand the relationships well first. As much I see here you might trying to have a bidirectional OneToOne relationship between Foo and Bar.
#Entity
#Table(name = "FOO")
Foo {
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "BAR_ID")
private Bar bar;
// getters and setters
}
#Entity
#Table(name = "BAR")
Bar{
#OneToOne(mappedBy = "bar")
private Foo foo;
// getters and setters
}
In the bidirectional association two sides of association exits –
owning and inverse. For one to one bidirectional relationships, the
owning side corresponds to the side that contains the appropriate
foreign key.
Here the owning side is the Foo and BAR_ID would be that foreign key. Having join column in both end doesn't make sense. And Relation will be cascaded from the Foo to Bar. And the inverse side is Bar here that needs to be annotated with mapped by value of the owning side reference.
Now if you set Bar object in Foo it will persist the Bar object along with the mapping with Foo. Doing the reverse thing doesn't make sense. isn't it ?
You are missing the opposite side of the relation.
If you say bar.setFoo(foo) then after you have to say foo.setBar(bar) or of course you can do this within the setFoo method as well.
Cascading means that it will trigger the operation on the relation, however in your case, the relation was unfinished as one side was missing.
Related
I have a Many-to-Many relationship between the class Foo and Bar. Because I want to have additional information on the helper table, I had to make a helper class FooBar as explained here: The best way to map a many-to-many association with extra columns when using JPA and Hibernate
I created a Foo, and created some bars (saved to DB). When I then add one of the bars to the foo using
foo.addBar(bar); // adds it bidirectionally
barRepository.save(bar); // JpaRepository
then the DB-entry for FooBar is created - as expected.
But when I want to remove that same bar again from the foo, using
foo.removeBar(bar); // removes it bidirectionally
barRepository.save(bar); // JpaRepository
then the earlier created FooBar-entry is NOT deleted from the DB.
With debugging I saw that the foo.removeBar(bar); did indeed remove bidirectionally. No Exceptions are thrown.
Am I doing something wrong?
I am quite sure it has to do with Cascading options, since I only save the bar.
What I have tried:
adding orphanRemoval = true on both #OneToMany - annotations, which did not work. And I think that's correct, because I don't delete neither Foo nor Bar, just their relation.
excluding CascadeType.REMOVE from the #OneToMany annotations, but same as orphanRemoval I think this is not for this case.
Edit: I suspect there has to be something in my code or model that messes with my orphanRemoval, since there are now already 2 answers who say that it works (with orphanRemoval=true).
The original question has been answered, but if anybody knows what could cause my orphanRemoval not to work I would really appreciate your input. Thanks
Code: Foo, Bar, FooBar
public class Foo {
private Collection<FooBar> fooBars = new HashSet<>();
// constructor omitted for brevity
#OneToMany(cascade = CascadeType.ALL, mappedBy = "foo", fetch = FetchType.EAGER)
public Collection<FooBar> getFooBars() {
return fooBars;
}
public void setFooBars(Collection<FooBar> fooBars) {
this.fooBars = fooBars;
}
// use this to maintain bidirectional integrity
public void addBar(Bar bar) {
FooBar fooBar = new FooBar(bar, this);
fooBars.add(fooBar);
bar.getFooBars().add(fooBar);
}
// use this to maintain bidirectional integrity
public void removeBar(Bar bar){
// I do not want to disclose the code for findFooBarFor(). It works 100%, and is not reloading data from DB
FooBar fooBar = findFooBarFor(bar, this);
fooBars.remove(fooBar);
bar.getFooBars().remove(fooBar);
}
}
public class Bar {
private Collection<FooBar> fooBars = new HashSet<>();
// constructor omitted for brevity
#OneToMany(fetch = FetchType.EAGER, mappedBy = "bar", cascade = CascadeType.ALL)
public Collection<FooBar> getFooBars() {
return fooBars;
}
public void setFooBars(Collection<FooBar> fooBars) {
this.fooBars = fooBars;
}
}
public class FooBar {
private FooBarId id; // embeddable class with foo and bar (only ids)
private Foo foo;
private Bar bar;
// this is why I had to use this helper class (FooBar),
// else I could have made a direct #ManyToMany between Foo and Bar
private Double additionalInformation;
public FooBar(Foo foo, Bar bar){
this.foo = foo;
this.bar = bar;
this.additionalInformation = .... // not important
this.id = new FooBarId(foo.getId(), bar.getId());
}
#EmbeddedId
public FooBarId getId(){
return id;
}
public void setId(FooBarId id){
this.id = id;
}
#ManyToOne
#MapsId("foo")
#JoinColumn(name = "fooid", referencedColumnName = "id")
public Foo getFoo() {
return foo;
}
public void setFoo(Foo foo) {
this.foo = foo;
}
#ManyToOne
#MapsId("bar")
#JoinColumn(name = "barid", referencedColumnName = "id")
public Bar getBar() {
return bar;
}
public void setBar(Bar bar) {
this.bar = bar;
}
// getter, setter for additionalInformation omitted for brevity
}
I tried this out from the example code. With a couple of 'sketchings in' this reproduced the fault.
The resolution did turn out to be as simple as adding the orphanRemoval = true you mentioned though. On Foo.getFooBars() :
#OneToMany(cascade = CascadeType.ALL, mappedBy = "foo", fetch = FetchType.EAGER, orphanRemoval = true)
public Collection<FooBar> getFooBars() {
return fooBars;
}
It seemed easiest to post that reproduction up to GitHub - hopefully there's a further subtle difference or something I missed in there.
This is based around Spring Boot and an H2 in-memory database so should work with no other environment - just try mvn clean test if in doubt.
The FooRepositoryTest class has the test case. It has a verify for the removal of the linking FooBar, or it may just be easier to read the SQL that gets logged.
Edit
This is the screenshot mentioned in a comment below:
I've tested your scenario and did the following three modifications to make it work:
Added orphanRemoval=true to both of the #OneToMany getFooBars() methods from Foo and Bar. For your specific scenario adding it in Foo would be enough, but you probably want the same effect for when you remove a foo from a bar as well.
Enclosed the foo.removeBar(bar) call inside a method annotated with Spring's #Transactional. You can put this method in a new #Service FooService class. Reason: orphanRemoval requires an active transactional session to work.
Removed call to barRepository.save(bar) after calling foo.removeBar(bar).
This is now redundant, because inside a transactional session changes are saved automatically.
Java Persistence 2.1. Chapter 3.2.3
Operation remove
• If X is a new entity, it is ignored by the remove operation.
However, the remove operation is cascaded to entities referenced by X,
if the relationship from X to these other entities is annotated with
the cascade=REMOVE or cascade=ALL annotation element value.
• If X is
a managed entity, the remove operation causes it to become removed.
The remove operation is cascaded to entities referenced by X, if the
relationships from X to these other entities is annotated with the
cascade=REMOVE or cascade=ALL annotation element value.
Check that you already use operation persist for you Entities Foo(or FooBar or Bar).
I have the following entities:
#Entity
public class Foo {
#ManyToOne(optional = false) // I've tried #OneToOne also, same result
#JoinColumn(name = "bar_id")
private Bar bar;
// this is a business key, though not mapped as unique for legacy reasons
#Column(nullable = false)
private long fooNo;
// getters/setters + other properties
}
#Entity
public class Bar {
#OneToOne(optional = true, mappedBy = "bar", cascade = CascadeType.ALL)
private Foo foo;
// getters/setters + other properties
}
NOTE: This is the correct mapping: #ManyToOne and #OneToOne (it wasn't designed by me). I have tried #OneToOne on both sides also, with the same result.
Basically, I can have a Bar without a Foo object, but everytime I have a Foo, there has to be a Bar associated with it. Foo is considered the parent object (which is why its the owner of the association), but Bar can stand alone in certain cases.
I then load a Foo object like this:
SELECT f FROM Foo f WHERE f.fooNo = :fooNo
foo.getBar() correctly fetches the appropriate Bar, as expected. However, foo.getBar().getFoo() is null. It seems the other side of this relationship is not correctly initialized by JPA/hibernate. Any ideas why this is happening and how I can fix it?
I use Hibernate 3.2.1 as my JPA implementation, which we are using through EJB3 beans (though that is probably irrelevant).
Are you sure about your assotiation? ManyToOne usually implies oneToMany on other.
I have a fairly straightforward one-to-many relationship
[SampleAliasMask] has many [SampleAliasMaskPart]
My problem is that when I persist a new instance of SampleAliasMask with collection parts I get an constraint violation that the foreign key link from the tables of SampleAliasMaskPart to SampleAliasMask is being set to NULL.
I am mapping using hibernate annotations as such:
#Entity
#Table(name="SAMPLE_ALIAS_MASK")
public class SampleAliasMask extends ClientEntity {
#OneToMany(mappedBy = "sampleAliasMask", fetch = FetchType.EAGER, cascade = javax.persistence.CascadeType.ALL, orphanRemoval = true)
#Cascade(CascadeType.ALL)
#Length(min = 1, message = "The sample alias mask must have components")
private Set<SampleAliasMaskPart> components;
With the other half of the relationship mapped as so:
#Entity
#Table(name="SAMPLE_ALIAS_MASK_PART")
public class SampleAliasMaskPart extends ClientEntity {
#ManyToOne(optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "SAMPLE_ALIAS_MASK_ID", nullable = false)
private SampleAliasMask sampleAliasMask;
The relevant part of ClientEntity is
#MappedSuperclass
public abstract class ClientEntity {
#Id
#Column(name="ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
I am creating the parts like this:
HashSet<SampleAliasMaskPart> components = new HashSet<>();
for(Map<String, Object> c : this.components) {
SampleAliasMaskPart component = new SampleAliasMaskPart(Integer.parseInt(c.get("value").toString(), 10), c.get("name").toString());
result.validate(component);
components.add(component);
}
mask.setComponents(components);
The exact error I get is:
java.sql.BatchUpdateException: ORA-01400: cannot insert NULL into ("ST"."SAMPLE_ALIAS_MASK_PART"."SAMPLE_ALIAS_MASK_ID")
I suspect the issue has to do with the fact that I never explicitly set SampleAliasMaskPart.sampleAliasMask but why do I need to? That relationship is never exposed nor navigated. That field is only there for mapping purposes which makes me think that I'm mapping this wrong.
Your assumption is correct. Hibernate uses the owning side of an association to know is the association exists or not. And the owning side ai the side where there is no mappedBy attribute.
The general rule is that when you have a bidirectional association, it's your responsibility to make the object graph coherent by initializing/modifying both sides of the association. Hibernate doesn't care much about it, but if you don't initialize the owning side, it won't persist the association.
Note that you're not forced to make this association bidirectional. If you don't, then adding the part to the mask will be sufficient, because this side (which is the unique side) is the owning side.
JB Nizet suggested correctly. There are two ways you can solve it:
Removing the bi-directional relationship:Remove the annotation #ManyToOne(optional = false, fetch = FetchType.LAZY) from the simpleAliasMask in SampleAliasMaskPart
Add the mask to each component by doing something like component.setSimpleAliasMask(mask). This will do the bidirectional relationship.
Merged with Referential integrity with One to One using hibernate.
I have following Entity -
#Entity
public class Foo {
#Id
private Long id;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "foo")
private Bar bar;
// getters/setters omitted
}
#Entity
public class Bar{
#id
private Long id;
#OneToOne
#JoinColumn(name = "foo_id", nullable = false)
private Foo foo;
// getters/setters omitted
}
I kept the relation like this because I want to keep the Id of Foo in Bar table so I can have delete cascade constraints through SQL at DB end
Now this causes another issues -
If I change the reference of Bar in Foo then hibernate doesn't delete the existing Bar but adds the another entry.
I need to delete existing Bar explicitly before assigning new one for update.
What I would like to know is - can I achieve the same DB layout with Foo as a owning side, so If I assign the new Bar I'll just assign it and Hibernate will internally delete the existing not required entry.
I am attempting to persist/merge a brand new object graph through jpa but it seems like the order of persistance is incorrect as it tries to save sub objects who have a constraint on their parent being present.
public class ObjectA implements Serializable {
...
#OneToMany(cascade = CascadeType.ALL, mappedBy = "objectAId")
private List<ObjectB> objectBList;
...
}
and
public class ObjectB implements Serializable {
...
#JoinColumn(name = "OBJECT_A_ID", referencedColumnName = "ID", nullable = false)
#ManyToOne(optional = false)
private ObjectA objectAId;
...
}
I will create a new entity ObjectA and along with several new ObjectB entities and add them to Object A. When i merge ObjectA I get the following:
org.hibernate.PropertyValueException: not-null property references a null or transient value: com.mycompany.data.ObjectB.objectAId
What am I missing or doing wrong?
It's your responsibility to keep both sides of bidirectional relationship in consistent state for objects in memory. In other words, when you add ObjectB to ObjectA.objectBList, you also should make ObjectB.objectAId pointing to the corresponding ObjectA.
Moreover, without optional = false you would be able to persist objects without errors, but the relationship between them wouldn't be persisted if ObjectB.objectAId is null. It happens because Hibernate looks at the state of the owning side of relationship when saving it to the database, and in the case of bidirectional one-to-many relationship owning side is the "many" side (ObjectB)