如果在JPA中将共享主键作为一对一关系时如何访问对象?

时间:2016-12-16 01:02:32

标签: java mysql entity-framework hibernate jpa

让我们来看看表结构: -

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`);

地址&客户通过id通过一对一关系进行映射。这是customer.id分配给address_id [I know that a column of a table may role as a primary-key which is generated from some other table]。

让我们看一下实体: -

@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
        );
    }

}

控制器类: -

@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;
    }
}

问题: -

我关注JPA Hibernate One-to-One relationship

  1. /customer-with-address/5属于递归。如何逃避递归
  2. /save-customer-with-address在将数据保存到数据库后,将地址返回null作为null。这是因为地址未设置为客户对象。当我尝试将地址设置为客户对象时,它也属于递归。那么,如何设置/获取地址对象/与客户对象?
  3. I one-to-one映射由任何实体完成,就像我之前做的那样。但这里的映射是从两侧完成的。 我可以从任何一方做吗?
  4. N.B: - 如果我将额外的列customer_id添加到地址表,则可以轻松解决所有问题。但我不想添加customer_id。我提前感谢您的宝贵意见。

1 个答案:

答案 0 :(得分:0)

  1. 检查您是以递归方式调用方法还是调试它
  2. 在客户

    中使用setter

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

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