Question

Is it possible to expose a manytomany relationship that uses a join entity (that contains extra data columns), below is my entities;

I'm trying to get 'purchases' to show in REST, I've put in 'products' as an example of a working REST mapping;

@Entity
public class User {

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

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = Purchase.class, orphanRemoval = true)
    @JoinColumn(name = "user_id", updatable = false)
    private List<Purchase> purchases = new ArrayList<>();

    @ManyToMany
    @JoinColumn(name = "user_id", updatable = false)
    private List<Product> products = new ArrayList<>();

}

@Entity
public class Product {

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

    private String name;

}

@Entity
public class Purchase implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @ManyToOne
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    private User user;

    @ManyToOne(targetEntity = Prodect.class)
    @JoinColumn(name = "product_id", referencedColumnName = "id")
    private Product product;

    @Column(name = "purchase_date")
    private Date purchaseDate;

}

So if i send the REST call;

[GET http://localhost:8080/webapp/users/1]

It returns links for [http://localhost:8080/webapp/users/1/products] but not for [http://localhost:8080/webapp/users/1/purchases]

Was it helpful?

Solution

worked out what the issue was; I need to create a JpaRepository for the Purchase entity. Soon as I added that, the REST links for purchases are available.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top