JPA: Custom constraint on #OneToMany field - java

I have the following scenario:
#Entity public class Foo {
#Id private Long id;
#OneToMany(mappedBy = "foo")
#MyCustomConstraint
private Set<Bar> bars;
}
#Entity public class Bar {
// ...
#ManyToOne(optional = false)
Foo foo;
}
I have autogenerated code (i.e. can't modify it) that creates a new Bar and adds it to an existing Foo by calling bar.setFoo(foo). setFoo makes sure the bar is added to foo's collection too. Then the autogenerated code calls persist(bar). At this point I need the custom constraint validator on foo.bars to be run (the newly added bar might violate it), but it isn't.
My questions:
Is this by design or am I doing something wrong?
What can I do to make it work?
Edit:
Some more information about the custom constraint - although I don't think that's particularly relevant to the question.
It's just a javax.validation custom constraint:
#javax.annotation.Constraint(validatedBy = MyCustomConstraintValidator.class)
#AllTheOtherAnnotationStuff
public #interface MyCustomAnnotation {
}
public class MyCustomConstraintValidator implements ConstraintValidator<MyCustomConstraint, Set /*<Bar>*/ .class> {
void initialize(MyCustomConstraint a) {}
boolean isValid(Set /*<Bar>*/ s, ConstraintValidatorContext ctx) { ... }
}
If I call entityManager.persist(foo), the constraint is validated. If I call entityManager.persist(bar), it is not, even though the bar was newly added to its Foo's collection.

The problem is that when you try to persist bar, you don't persist its foo automatically. You have to explicitly specify in the #ManyToOne annotation that you want to cascade the persist operation or you have to persist foo manually.
#ManyToOne(optional = false, cascade = CascadeType.PERSIST)
Foo foo;

Related

Spring and JPA 2.0 - Composite key in many to many relationship with extra column

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;
}

Thread safe spring data delete

I have two entities with one-to-one association. And some services that works with them in parallel. I need to delete one, but sometimes i have DataIntegrityViolationException, that as i understand means that i can't delete some entity while other has foreign key on it.
Here is my entities:
public class Foo{
#Id
#GeneratedValue
private Long id;
}
and:
public class Bar{
#Id
#GeneratedValue
private Long id;
#ManyToOne
private Foo foo;
}
Method that doesn't work (all repos extends from JpaRepository):
#Transactional
public void deleteFoo(Long fooId) {
barRepository.deleteAllByFooId(fooId);
fooRepository.deleteById(fooId);
}
And some method that works in parallel and breaks everything:
#Transactional
public void method(Long fooId) {
...
Foo foo = fooRepository.findById(fooId);
barRepository.save(new Bar(foo));
...
}
So i have ConstraintViolationException, as i understand because im trying to delete Foo but i have that new Bar(foo) in method that wasn't deleted by barRepository.deleteAllByFooId(fooId) in deleteFoo .
I need some approach like "delete method should wait until all current transactions finishes and then run only one transaction".
Can't use KeyLockManager because real structure of project already enough complicated and if i use it it should be same lock in many classes.
The problem is that you try to delete entity that being used in transaction. To close transaction you could use repository's save() method.
Also you should look at cascades and orphan removal. Use like this:
In Bar entity:
#ManyToOne(cascade = CascadeType.REMOVE, orphanRemoval = true)
private Foo foo;
And delete like so:
barRepository.save(bar);
or so:

Hibernate Many-to-Many with join-class Cascading issue

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).

Lazy-loading association does not properly initialize child association

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.

How to map this OnetoOne in hibernate using JPA

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.

Categories