Search code examples
hibernatequarkusquarkus-panache

Saving Entity referencing other by just id using Panache


I have these 2 classes:

Writer

@Entity
public class Writer extends PanacheEntity {
    public String name;

    public Writer() {
    }
}

Book

@Entity
public class Book extends PanacheEntity {
    public String name;
    @OneToOne
    public Writer writer;

    public Book() {}
}

The resource class is:

@Path("/books")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class BookResource {

    @GET
    public List<Book> list() {
        return Writer.listAll();
    }

    @GET
    @Path("/{id}")
    public Book get(Long id) {
        return Book.findById(id);
    }

    @POST
    @Transactional
    public Response create(Book book) {
        book.persist();
        return Response.created(URI.create("/book/" + book.id)).build();
    }
}

The data comming to the @POST method is a json like:

{
    "name":"bookName",
    "writer_id":1
}

How can I save it using the writer_id to correct reference the writer? This way the database does not make it correctly: enter image description here


Solution

  • It was possible passing the correct json to the @POST method:

    {
        "name":"bookName",
        "writer": {"id":1}
    }