Is there a way to return the full details of a joined entity instead of a link? In the example below I want to also return the details of the product, if I have list of 100 purchases, it would avoid having to make 100 calls to get the product details.
The repositories for Product, User and Purchase entities are all created using spring-data-jpa
{
"_embedded" : {
"purchase" : [ {
"_links" : {
"product" : {
"href" : "http://localhost:8080/webapp/purchase/1/product"
},
"user" : {
"href" : "http://localhost:8080/webapp/purchase/1/user"
}
},
"purchasedOn" : "2014-02-23",
"amount" : 1
} ]
}
}
Entities and Repositories;
@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<>();
}
@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(fetch = FetchType.EAGER, targetEntity = Product.class)
@JoinColumn(name = "product_id", referencedColumnName = "id")
private Product product;
@Column(name = "purchase_date")
private Date purchaseDate;
private Integer amount;
}
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase, Long> {}
If we create our repository by extending the CrudRepository interface, we have to provide two type parameters: The type of the entity that is managed by our repository. The type of the entity's id field.
Each of these defines its own functionality: CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.
Spring Data REST can be used to expose HATEOAS RESTful resources around Spring Data repositories. Without writing a lot of code, we can expose RESTful API around Spring Data Repositories.
Spring Data REST builds on top of Spring Data repositories, analyzes your application's domain model and exposes hypermedia-driven HTTP resources for aggregates contained in the model.
It would seems there is already a New Feature request for this functionality;
https://jira.springsource.org/browse/DATAREST-221
https://jira.springsource.org/browse/DATAREST-243
I'll leave the question open until the feature has been implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With