
Question:
I've implemented @ManyToMany mapping with an EmbeddedId class, as per the example provided by @Vlad Mihalcea. It works, however I need to create and use Spring's REST repository for this JoinTable Entity.
Usually, I would do something like this to enable the repository:
@CrossOrigin
@RepositoryRestResource(collectionResourceRel = "companyproducts", path = "companyproducts")
public interface CompanyProductRepository
extends PagingAndSortingRepository<CompanyProduct, CompanyProduct.CompanyProductId> {
}
But, since in this Entity (JoinTable) I don't have a classic id
, like this:
public class FooBar {
....
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
}
but instead I have:
public class FooBar {
....
@EmbeddedId
private FooBarId id;
...
}
I cannot use Long
or let's say int
because the identifier is not of any of those types, it's basically of type FooBarId
.
By the way, I will also provide most of that class:
@Embeddable
public class FooBarId implements Serializable {
@Column(name = "foo_id")
private Long fooId;
@Column(name = "bar_id")
private Long barId;
private FooBarId() {}
public FooBarId(Long fooId, Long barId) {
this.fooId= fooId;
this.barId= barId;
}
...
}
I did try, of course, putting FooBarId
instead of Long
in the repository declaration, but then in my REST json response I get something like this:
http://localhost:8080/api/foobar/com.example.springrest.entities.foobarid@g43
(note the path to the class itself, not a numeral parameter, eg. 5).
My question is: Is it possible to use repositories with an EmbeddedId
instead of Long
, int
, etc.?
Yes of course
public interface FooBarRepository extends PagingAndSortingRepository<FooBar, FooBarId > { }
the id is the embeddable class so use that instead of the classic primitive.
the problem in the response is probably something related to your save/retrieve logic
<strong>Edit</strong>: based on the response being the class instead of the numeral i expect you retrieved the id from the repository, but you should obviously get the numerical value from the id since now that id is the embeddable class