couchdbektorp

one-to-one association in Ektorp


Is it possible to define a one-to-one association in Ektorp? In the Ektorp documentation I only found how to embed a list of objects into an object referenced by foreign key. I want to produce a document like:

{
  name: "John",
  surname: "Smith",
  address: {
    street: "Abc Street",
    zip: "12345",
    city: "My City"
  }
}

Thanks


Solution

  • Embedding a complete document like this is very friendly. One straightforward way to do this is by defining a Contact class that has an Address class.

    // Contact.java
    package com.example;
    
    public class Contact extends org.ektorp.support.CouchDbDocument {
        private String name;
        private String surname;
        private Address address;
    
        //... constructors and/or setters
    
        public String getName() { return name; }
        public String getSurname() { return surname; }
        public Address getAddress() { return address; }
    }
    
    // Address.java
    package com.example;
    
    public class Address {
        private String street;
        private String zip;
        private String city;
    
        //... constructors and/or setters
    
        public String getStreet() { return street; }
        public String getZip() { return zip; }
        public String getCity() { return city; }
    }
    

    When written to the database, it will produce a document that looks like:

    {
       "_id": "590ede48b04e7c61914c677f0f000b57",
       "_rev": "1-fae3423a6ea58741dca18764a39e48a9",
       "name": "John",
       "surname": "Smith",
       "address": {
           "street": "Abc Street",
           "zip": "12345",
           "city": "My City"
       }
    }