I have a Spring Boot application using Spring JPA, and what I'm trying to do is to save a new entity that has some foreign keys by just providing the IDs of those child entities. So, like:
@Table(name = "PERSON")
public class Person {
@Column(name = "PET_GUID")
public Pet pet;
}
Using this, I'd like to be able to have my PersonRepository that implements CrudRepository save a Person by just providing the guid of the Pet. Using straight up hibernate I can do that using EntityManager.getReference. I know that I can inject an EntityManager into my Entity or Repository and do something that way, but is there an easier way? I tried just doing person.setPet(new Pet(myPetsGuid)), but I get a "foreign key not found" when doing that, so that does not seem to work.
First, you should add @ManyToOne relation to the pet
property:
@Entity
@Table(name = "PERSON")
public class Person {
//...
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "pet_guid")
privat Pet pet;
}
It says to Hibernate to use a foreign key to the Pet
entity (and its table).
Second, you should use the method getOne
of your PersonRepository
to get a reference to the Pet
entity, for example:
@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);
}
}