0

Let's have a look at table structure:-

CREATE TABLE `customer` (
  `id` bigint(20) UNSIGNED AUTO_INCREMENT NOT NULL,
  `first_name` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` varchar(150) COLLATE utf8_unicode_ci NOT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `customer` ADD PRIMARY KEY (`id`);

-------------------------------------------------------------

CREATE TABLE `address` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `street` varchar(512) COLLATE utf8_unicode_ci NOT NULL,
  `city` varchar(512) COLLATE utf8_unicode_ci NOT NULL,
  `country` varchar(512) COLLATE utf8_unicode_ci NOT NULL,
  `postal_code` varchar(512) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `address` ADD PRIMARY KEY (`id`);

address & customer mapped through one-to-one relationship via id. That is customer.id is assigned to address_id [I know that a column of a table may role as a primary-key which is generated from some other table].

Lets look at entities:-

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;

    @OneToOne
    @PrimaryKeyJoinColumn
    private Address address;

    // getters & setters

    @Override
    public String toString() {
        return String.format(
            "Customer[id=%d, firstName='%s', lastName='%s', address='%s']",
            id, firstName, lastName, address
        );
    }
}

//////////////////////////////////////////////////////////////////////////

@Entity
public class Address {

    @Id @GeneratedValue(generator = "customForeignGenerator")
    @org.hibernate.annotations.GenericGenerator(
            name = "customForeignGenerator",
            strategy = "foreign",
            parameters = @Parameter(name = "property", value = "customer")
    )
    private Long id;
    private String street;
    private String city;
    private String country;
    private String postalCode;

    @OneToOne(mappedBy="address")
    @PrimaryKeyJoinColumn
    public Customer customer;

    // getters & setters

    @Override
    public String toString () {
        return String.format(
            "Address[id='%d', street='%s', city='%s', country='%s', postalCode='%s']",
            id, street, city, country, postalCode
        );
    }

}

controller class:-

@RestController
@RequestMapping("/api/customers")
public class CustomerRestController {

    // CustomerRepository extends CrudRepository<Customer, Long>
    @Autowired
    private CustomerRepository customerRepository;

    // AddressRepository extends CrudRepository<Address, Long>
    @Autowired
    private AddressRepository addressRepository;

    @RequestMapping("/customer-with-address/{customerId}")
    public Customer getCustomerWithAddress(@PathVariable("customerId") Long customerId) {
        return customerRepository.findOne(customerId);
    }

    @RequestMapping("/save-customer-with-address")
    public Customer getCustomer() {
        Customer customer = new Customer();
        customer.setFirstName("ABC");
        customer.setLastName("XYZ");
        Customer customer1 = customerRepository.save(customer);

        Address address = new Address();
        address.setStreet("street " + customer1.getId());
        address.setCity("city " + customer1.getId());
        address.setCountry("country " + customer1.getId());
        address.setPostalCode("postal_code " + customer1.getId());
        address.setCustomer(customer1);
        addressRepository.save(address);

        return customer;
    }
}

Problem:-

I follow JPA Hibernate One-to-One relationship

  1. /customer-with-address/5 falls into recursive. How can I escape from recursion?
  2. /save-customer-with-address returns address as null with customer object after saving data into the database. This is because address is not set to customer object. When I am trying to set address to customer object, it also fall into the recursive. So, how can I set/get the address object to/with customer object?
  3. I one-to-one mapping done by from any Entity as I do before. But here mapping is done from both side. Can I do from any side?

N.B:- All the problems can be solved easily if I put an extra column customer_id to the address table. But I would not like to add customer_id. I appreciate your valuable opinion in advance.

Community
  • 1
  • 1
testuser
  • 793
  • 3
  • 13
  • 35

1 Answers1

0
  1. check if you are calling method recursively or debug it
  2. with setter in customer

    setAddress(a){ a.setCustomer(this); this.address=a; }

  3. https://en.wikibooks.org/wiki/Java_Persistence/OneToOne#Example_of_an_inverse_OneToOne_relationship_annotations

Peter Šály
  • 2,848
  • 2
  • 12
  • 26