Jump to content

Wikipedia:Reference desk/Archives/Computing/2018 May 20

From Wikipedia, the free encyclopedia
Computing desk
< May 19 << Apr | May | Jun >> May 21 >
Welcome to the Wikipedia Computing Reference Desk Archives
The page you are currently viewing is an archive page. While you can leave answers for any questions shown below, please ask new questions on one of the current reference desk pages.


May 20

[edit]

Problem with JPA many-to-many linking

[edit]

I'm having problems with JPA (Java Persistence API) models and queries at work. Our database model has a many-to-many relationship between two kinds of objects, let's call them Foo and Bar. So every Foo can be linked to many different Bars and the other way around.

I need to implement an API to this model in JPA queries. I tried making three tables, foo, bar and foo_bar, where the third one only consists of two columns: foo_id and bar_id, which link to the id columns of the first two tables, marking which Foo and which Bar objects are linked.

I first tried to make this kind of query methods in JPA repositories:

public class FooRepository extends JPARepository<Foo, String> {
@Query("select fb.foo from FooBar fb where fb.bar = ?1")
public List<Foo> findByBar(Bar bar);
}

public class BarRepository extends JPARepository<Bar, String> {
@Query("select fb.bar from FooBar fb where fb.foo = ?1")
public List<Bar> findByFoo(Foo foo);
}

with classes Foo, Bar and FooBar respectively, each annotated with @Entity.

This resulted in an error that FooBar doesn't have an ID field of its own and thus can't be an entity. I removed the @Entity annotation from FooBar and this time I got an error that FooBar is not mapped.

I don't know how to proceed. Am I required to add an ID field to the FooBar object too, even though all it does is link Foos and Bars together and doesn't possess any information, state or semantics of its own? JIP | Talk 16:11, 20 May 2018 (UTC)[reply]