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?

Carmine
1#
Carmine Published in 2017-12-07 09:07:12Z

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

@Getter
@Setter
@Entity
public abstract class FinancialObject {

    @Id
    @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

@Getter
@Setter
@Entity
public class FinancialObjectToFinancialObjectRelation implements Serializable{

    @Id
    @JoinColumn
    @ManyToOne
    private FinancialObject sourceFinancialObject;

    @Id
    @JoinColumn
    @ManyToOne
    private FinancialObject targetFinancialObject;

    @Column
    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.setSourceFinancialObject(object2);
relation.setTargetFinancialObject(object3);
relation.setRelationType("Custom relation type");

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

object1.getRelatedFinancialObjects().add(relation);

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.296076 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO