我正在使用spring boot 2.2.0和spring数据,我想在创建父对象后保存一个子实体。 这是我的课程
@Entity
@Table(schema = "public", name = "person")
@Inheritance(strategy = InheritanceType.JOINED)
public class Person implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "first_name", length = 100)
private String firstName;
...\\ getters and setters
}
@Table(name = "`owner`")
@PrimaryKeyJoinColumn()
public class Owner extends Person implements Serializable {
\\ some other properties
}
@Table(name = "`owner`")
@PrimaryKeyJoinColumn()
public class User extends Person implements Serializable {
\\ some more properties, username, etc
}
我正在使用JpaRepositroy
public interface PersonRepository extends JpaRepository<Person, Integer> {
}
public interface UserRepository extends JpaRepository<User, Integer> {
}
public interface OwnerRepository extends JpaRepository<Owner, Integer> {
}
我可以创建一个没有任何其他属性的人员,但对于子类,JPA还会尝试保存一个非目的的新人员,我的BO会像这样保存信息
class BOWithRepositories{
public OwnerDTO save(OwnerDTO dto) {
if (dto.getId() == null) {
throw new InvalidDataException("the id for the owner can not be empty or null");
}
Optional<Person> person = personRepository.findById(dto.getId());
if (!person.isPresent()) {
String message = String.format("The person with id %d does not exists, are trying to create a new Owner instead to convert a Person to owner?", dto.getId());
throw new EntityNotFoundException(message);
}
Owner owner = new Owner();
owner.setId(person.get().getId());
owner.setActiveBusNumber(0);
owner.setTotalBusNumber(0);
owner.setFirstName(person.get().getFirstName());
owner.setLastName(person.get().getLastName());
owner.setDocumentNumber(person.get().getDocumentNumber());
owner.setDocumentType(person.get().getDocumentType());
ownerRepository.save(owner);
dto = toDTO((Owner)person.get());
return dto;
}
}
我想将新的子类转换为父类。 我的意思是我想用一个Person的所有现有数据创建一个新所有者。