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.
Related
I have two entities Foo and Bar in many-to-many relationship. The joining entity is FooBar, and since this entity has another property (its own id), I used #ManyToOne on the owner side (FooBar) and #OneToMany in dependent entities (Foo and Bar). How to create a FooBarRepository extending CrudRepository without the explicit composite key field inside FooBar? Ideally, I don't want to change the members of my FooBar class.
I tried to use #IdClass, but I don't want to have fields fooId and barId inside FooBar and I am getting this exception:
Caused by: org.hibernate.AnnotationException: Property of #IdClass not found in entity com.nano.testers.test.FooBar: barId
I also tried to follow the documentation of IdClass and reference columns by name explicitly, but I failed (maybe the solution lies somewhere here?)
The names of the fields or properties in the primary key class and the primary key fields or properties of the entity must correspond and their types must be the same.
I tried to change the names of fields inside Foo and Bar to just id, so that they would be referenced as foo_id and bar_id in the joining table, but the exception was the same.
I don't want to use #EmbeddedId, if that means I need to have a field of FooBarPk type inside the FooBar class.
#Entity
public class Foo {
#Id
private Long fooId;
#OneToMany(mappedBy = "foo", cascade = CascadeType.ALL)
private Set<FooBar> foobars;
}
#Entity
public class Bar {
#Id
private Long barId;
#OneToMany(mappedBy = "bar", cascade = CascadeType.ALL)
private Set<FooBar> foobars;
}
#Entity
//#IdClass(FooBarPk.class)
public class FooBar implements Serializable {
#Id
private Long fooBarId;
#Id
#ManyToOne
#JoinColumn
private Foo foo;
#Id
#ManyToOne
#JoinColumn
private Bar bar;
}
public class FooBarPk implements Serializable {
private Long fooId;
private Long barId;
private Long fooBarId;
}
public interface FooBarRepository extends CrudRepository<FooBar, FooBarPk> {
}
It looks like the names of the fields in the composite key class have to be the same as names of the referenced entities. I think these names don't follow the clean code principles, but I will have to live with this solution for now.
public class FooBarPk implements Serializable {
private Long foo;
private Long bar;
private Long fooBarId;
}
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 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.
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 am using JPA (Hibernate) with the following entity class with one one-to-many relationship.
When I add elements to the list, and then persist the Organization entity, it adds the new elements to the proyects table, but when I remove elements from the list, nothing happens when persist (or merge), and I would like these elements to be removed from the database.
I tried also orphanRemoval=true in the OneToMany annotation, but it doesn't work.
#Entity
public class Organization {
#Id
#GeneratedValue
public long internalId;
#Basic
#Column(nullable = false, length = 100)
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "organization")
private List<Proyect> proyects;
// Getters and Setters
}
You need to set Proyect.organization to null and update that entity, since this property is responsible for the database entry (Proyect is the owning side in this case ).