smart987
smart987

Reputation: 832

need Spring Data JPA resource entry to make one many rest call

Using Spring Data jpa and Spring Data Rest I could able to get basic CRUD operations to work. But I am facing problem with one to many (owner -> car(s)) relationship. Can any one help me in this.

Owner.java

@Entity
@Table(name = "OWNER")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Owner implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private Integer age;

    @OneToMany(mappedBy = "owner")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Car> cars = new HashSet<>();


}

OwnerResource.java

    @RestController
    @RequestMapping("/api")
    public class OwnerResource {    
        private final Logger log = LoggerFactory.getLogger(OwnerResource.class);    
        @Inject
        private OwnerRepository ownerRepository;    

        @RequestMapping(value = "/owners",
                method = RequestMethod.POST,
                produces = MediaType.APPLICATION_JSON_VALUE)
        @Timed
        public ResponseEntity<Owner> create(@RequestBody Owner owner) throws URISyntaxException {
            log.debug("REST request to save Owner : {}", owner);
            if (owner.getId() != null) {
                return ResponseEntity.badRequest().header("Failure", "A new owner cannot already have an ID").body(null);
            }
            Owner result = ownerRepository.save(owner);
            return ResponseEntity.created(new URI("/api/owners/" + result.getId()))
                    .headers(HeaderUtil.createEntityCreationAlert("owner", result.getId().toString()))
                    .body(result);
        }

       @RequestMapping(value = "/owners",
            method = RequestMethod.PUT,
            produces = MediaType.APPLICATION_JSON_VALUE)
        @Timed
        public ResponseEntity<Owner> update(@RequestBody Owner owner) throws URISyntaxException {
            log.debug("REST request to update Owner : {}", owner);
            if (owner.getId() == null) {
                return create(owner);
            }
            Owner result = ownerRepository.save(owner);
            return ResponseEntity.ok()
                    .headers(HeaderUtil.createEntityUpdateAlert("owner", owner.getId().toString()))
                    .body(result);
        }

       @RequestMapping(value = "/owners",
                method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
        @Timed
        public ResponseEntity<List<Owner>> getAll(@RequestParam(value = "page" , required = false) Integer offset,
                                      @RequestParam(value = "per_page", required = false) Integer limit)
            throws URISyntaxException {
            Page<Owner> page = ownerRepository.findAll(PaginationUtil.generatePageRequest(offset, limit));
            HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/owners", offset, limit);
            return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
        }

 @RequestMapping(value = "/owners/{id}",
                method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
        @Timed
        public ResponseEntity<Owner> get(@PathVariable Long id) {
            log.debug("REST request to get Owner : {}", id);
            return Optional.ofNullable(ownerRepository.findOne(id))
                .map(owner -> new ResponseEntity<>(
                    owner,
                    HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
        }

    }

OwnerRepository.java

/**
 * Spring Data JPA repository for the Owner entity.
 */
public interface OwnerRepository extends JpaRepository<Owner,Long> {    


}

The basic crud operation is working fine for Owner. But now I need to get all cars of a particular owner for that I need to add one rest call entry in OwnerResource.java and a method entry in OwneRepository.java. I tried different ways but getting many errors and is not working. The following is what I tried.

In OwnerRepository.java

Owner findAllByOwnerId(Long id);//But eclipse shows error here for this method

In OwnerResource.java

//Get All Cars
    @RequestMapping(value = "/{id}/cars",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<Owner> getAll(@PathVariable Long id) {
        log.debug("REST request to get All Cars of the Owner : {}", id);
        return Optional.ofNullable(ownerRepository.findAllByOwnerId(id))
            .map(owner -> new ResponseEntity<>(
                owner,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

But these two changes are not working out. I am beginner to spring data jpa and spring data rest. Can any one help me in correcting these two so that I can get all cars of the owner.

Upvotes: 0

Views: 384

Answers (1)

Hatem Jaber
Hatem Jaber

Reputation: 2402

I believe it shows an error because the findAll returns a different type of object: List, Page, etc...

Try this:

List<Owner> findAllByOwnerId(@Param("id") Long id);

That will return you a list of objects. If you want to return with pagination, than you need this instead:

Page<Owner> findAllByOwnerId(@Param("id") Long id, Pageable pageable);

I hope this helps, let me know how it works for you.

Upvotes: 1

Related Questions