findByParent?

29 views
Skip to first unread message

Emmanouil Batsis (Manos)

unread,
Nov 26, 2012, 10:07:50 AM11/26/12
to resth...@googlegroups.com

Suppose you have a many to one model relationship between classes Child
and Parent, what it the currently correct way of implementing
findByParent(Id?) in your ChildController/Service/Repository?

Many thanks,

Manos

Emmanouil Batsis (Manos)

unread,
Nov 26, 2012, 11:01:46 AM11/26/12
to resth...@googlegroups.com
My own 2 tier solution for now is:


@Controller
@RequestMapping(value = "/api/child", produces = {"application/json",
"application/xml"})
public class ChildController extends
RepositoryBasedRestController<Child, Long, ChildRepository> {
//...
@RequestMapping(value = "parent/{id}", method = RequestMethod.GET)
@ResponseBody
public List<Comment> findByParent(@PathVariable Long id) {
List<Comment> comments = this.repository.findByParent(id);
return comments;
}
}


public interface ChildRepository extends JpaRepository<Child, Long> {

@Query("select c from Child c where c.parent.id = ?1")
public List<Comment> findByParent(Long id);
}

Manos

Seb

unread,
Nov 27, 2012, 10:30:53 AM11/27/12
to resth...@googlegroups.com
Hi,

This is a valid implementation.

Please note that you may take care of eventual circular references between Child and Parent POJO instances.

Such issue could be resolved by :
 - Using @JsonManagedReference and @JsonBackReference annotations as described here.
 - Or better, use Jackson 2 Object Identity feature as described here

Regards,
Sébastien Deleuze
Reply all
Reply to author
Forward
0 new messages