【问题标题】:Spring Jpa Entity - EntityManager.getReferenceSpring Jpa 实体 - EntityManager.getReference
【发布时间】:2019-03-16 01:24:35
【问题描述】:

我有一个使用 Spring JPA 的 Spring Boot 应用程序,我想做的是通过提供这些子实体的 ID 来保存一个具有一些外键的新实体。所以,比如:

@Table(name = "PERSON")
public class Person {
@Column(name = "PET_GUID")
public Pet pet;
}

使用这个,我希望能够让实现 CrudRepository 的 PersonRepository 通过提供 Pet 的 guid 来保存一个人。使用直接休眠我可以使用 EntityManager.getReference 来做到这一点。我知道我可以将 EntityManager 注入到我的 Entity 或 Repository 中并这样做,但是有没有更简单的方法?我尝试只做 person.setPet(new Pet(myPetsGuid)),但是这样做时我得到一个“找不到外键”,所以这似乎不起作用。

【问题讨论】:

    标签: spring hibernate spring-boot spring-data-jpa spring-boot-jpa


    【解决方案1】:

    首先,您应该将@ManyToOne 关系添加到pet 属性:

    @Entity
    @Table(name = "PERSON")
    public class Person {
    
        //...
    
        @ManyToOne(optional = false, fetch = FetchType.LAZY)
        @JoinColumn(name = "pet_guid")
        privat Pet pet;
    }
    

    它告诉 Hibernate 使用 Pet 实体(及其表)的外键。

    其次,你应该使用PersonRepository的方法getOne来获取Pet实体的引用,例如:

    @Service
    public class PersonService {
    
        private final PetRepository petRepo;
        private final PersonRepository personRepo;
    
        //...
    
        @NonNull
        @Transactional
        public Person create(@NonNull final PersonDto personDto) {
             Person person = new Person();
             //...
             UUID petId = personDto.getPetId();
             Pet pet = petRepo.getOne(perId);
             person.setPet(pet);
             //...
             return person.save(person);
        }
    
    }
    

    【讨论】:

    • 啊,是的,getOne 调用是我所缺少的。这就是我需要的!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 2020-08-23
    • 2015-09-11
    • 2020-09-16
    • 2012-07-16
    • 2016-03-30
    • 1970-01-01
    相关资源
    最近更新 更多