Home How to add Many-To-Many relationship in Spring Data JPA with strict mapping?
Reply: 0

How to add Many-To-Many relationship in Spring Data JPA with strict mapping?

user1868 Published in April 25, 2018, 10:54 am

I have an object I want to map to itself with Many-To-Many, but with some extra columns. Here's the class

public abstract class FinancialObject {

    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(mappedBy = "sourceFinancialObject",
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL,
            orphanRemoval = true
    private List<FinancialObjectToFinancialObjectRelation> relatedFinancialObjects;


And here's the relation itself

public class FinancialObjectToFinancialObjectRelation implements Serializable{

    private FinancialObject sourceFinancialObject;

    private FinancialObject targetFinancialObject;

    private String relationType;

Now the point is, I can add 2 other objects as a relation to my object relation list, which is not what I want to do

Here's the code example that breaks my logical rule

FinancialObject object1 = new FinancialObject();
FinancialObject object2 = new FinancialObject();
FinancialObject object3 = new FinancialObject();

FinancialObjectToFinancialObjectRelation relation = new FinancialObjectToFinancialObjectRelation();
relation.setRelationType("Custom relation type");

object1.setRelatedFinancialObjects(new ArrayList<FinancialObjectToFinancialObjectRelation>());


So I end up having object1s relation list having a relation between object2 and object3. Is there a way to avoid it?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.316768 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO