1

My back-end application gets json object via REST API, which exists in database but not exist in Caeynne ObjectContext, how to remove object by id via ObjectContext.

//  <dependency>
//      <groupId>org.apache.cayenne</groupId>
//      <artifactId>cayenne-server</artifactId>
//      <version>4.0.M5</version>
//  </dependency>

import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.configuration.server.ServerRuntime;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cayenne.test.model.Artist;

@RestController
@RequestMapping(value = "/rest")
public class ArtistRestController {

    @DeleteMapping(value = "/artist")
    public ResponseEntity deleteArtist(@RequestBody Artist artist) {

        ServerRuntime runtime = ServerRuntime
                .builder()
                .addConfig("cayenne-cayenne_test.xml")
                .build();

        ObjectContext context = runtime.newContext();

        // don't work
        context.deleteObject(artist);
        context.commitChanges();

        return new ResponseEntity<>(HttpStatus.OK);
    }
}
Yuriy Bochkarev
  • 79
  • 1
  • 10

1 Answers1

1
  1. If you object have all it's properties and ObjectId properly set you can do something like this:
context.localObject(myObject);
context.deleteObject(myObject);
context.commitChanges();
  1. If you have only raw id you should create object first:
MyObject myObject = Cayenne.objectForPk(context, MyObject.class, id);
context.deleteObject(myObject);
context.commitChanges();

In this case you object probably will be fetched from the database, to restore actual state of it and to track all relationships that can be deleted along with this object.

Nikita
  • 266
  • 2
  • 7
  • Object have all it's properties, Your example don't work. – Yuriy Bochkarev Aug 24 '17 at 02:49
  • ObjectId is not a regular property it's internal field used by Cayenne, if you REST service isn't aware of it it can be missing and object will be treated as new. – Nikita Aug 24 '17 at 12:24