RESTful using Jersey: method to POST multiple entities
Asked Answered
F

1

8

I am trying to develop a method in my RESTful web service in Java to insert multiple entries into a MySQL DB using POST request. The generated RESTful Web Service has a method to insert a single entity, but not multiple ones. For example, it accepts:

<creature>
  <sort>Mouse</sort> 
  <name>Pinky</name>
</creature>

But not (what I would like):

<creature>
  <sort>Mouse</sort> 
  <name>Pinky</name>
</creature>
<creature>
  <sort>Elephant</sort> 
  <name>Dumbo</name>
</creature>

I'm guessing that you have to loop through the entities, but not sure how to implement it, being a shameful novice.

Fjord answered 24/8, 2010 at 6:4 Comment(0)
M
5

Just ran into this myself. I need transactional posts of multiple items, so iterating on the client is out of the question. The consensus seems to be that you need to use a separate path from your normal resources:

http://chasenlehara.com/blog/creating-restful-web-services/ (Multi-resources)

RESTful way to create multiple items in one request

I couldn't find much about how to do this with Jersey, though. As it turns out, it's pretty easy. You should already have multi-entity converter and resource classes for GET requests, you just need to specify a path where the server can assume it's going to receive them:

@Path("creatures")
@Stateless
public class CreaturesResource {

...

    @POST
    @Consumes({"application/xml", "application/json"})
    public Response post(CreatureConverter data) {
       Creature entity = data.resolveEntity(em);
        postCreature(entity);
    }

    @POST @Path("multi")
    @Consumes({"application/xml", "application/json"})
    public Response postMulti(CreaturesConverter data) {
       Collection<Creature> entities = data.getEntities();
       for (Creature c : entities) {
            postCreature(c);
       }
    }

Then instead of posting

<creature />

to

http://.../resources/creatures

You would post

<creatures>
    <creature />
    <creature />
</creatures>

to

http://.../resources/creatures/multi
Mitchmitchael answered 11/12, 2010 at 11:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.