Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful using Jersey: method to POST multiple entities

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.

like image 427
lemons Avatar asked Aug 24 '10 06:08

lemons


Video Answer


1 Answers

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
like image 188
Tim Sylvester Avatar answered Oct 19 '22 06:10

Tim Sylvester