Spring Data JPA保存子级而不获取父级

Evg*_*rov 7 java spring hibernate jpa spring-data

如果您知道父 ID,如何使用 Spring data JPA 存储库保存子实体?

例如,如果我们有一对多关系:

@Entity
public class Customer {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;
    @ManyToOne
    private CustomerCategory category;
}

@Entity
public class CustomerCategory {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String name;
}
Run Code Online (Sandbox Code Playgroud)

人们可以做这样的事情:

CustomerCategory someCategory = customerRepository.findOne(1L);// how to skip that line. The id should be enough. 
Customer cust = new Customer("Evgeni", "Dimitrov", someCategory);           
customerRepository.save(cust);
Run Code Online (Sandbox Code Playgroud)

JPA 可以做到load(只需创建代理并设置 Id)而不是“获取”(从数据库中选择)。Spring Data JPA 可以实现这一点吗?

小智 -1

忘记身份证号 您现在处于 ORM (ObjectRelationMapping) 的对象级别。对象是由其他对象组成的。没有身份证。

  • 正如目前所写的,您的答案尚不清楚。请[编辑]添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以[在帮助中心](/help/how-to-answer)找到有关如何写出好的答案的更多信息。 (2认同)