Spring Data JPA单向OneToOne映射不会持久

时间:2018-12-16 20:07:12

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

我有一个Client数据类型(代表一个客户),其主体类型为Person,联系人类型为Contact(联系方式)。

客户端数据类型(带有映射)为:

@Entity
public class Client {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Access(AccessType.PROPERTY)
    private Long id;

    @Column(unique = true, updatable = false)
    private String nk;

    @Min(10000000000L)
    private Long abn;

    private String name;

    @OneToOne(cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
    @JoinColumn(name = "person_id")
    private Person principal;

    @OneToOne(cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
    @JoinColumn(name = "contact_id")
    private Contact contact;

    public Client() {
        this.nk = UUID.randomUUID().toString();
    }

    // remaining constructors, builders and accessors omitted for brevity
}

以联系人为例(人员的结构相同)

@Entity
public class Contact {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    private String phone;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String mobile;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String fax;

    @OneToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
    @JoinColumn(name = "address_id")
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Address address;

    private String email;

    public Contact() {
    }
    // remaining constructors, builders and accessors omitted for brevity
}

Address数据类型也是单向映射。我可以显示“人”和“地址”,但是我很确定不会从中了解任何新内容。

不幸的是,通过所有者和操作员字段,客户是与飞机的ManyToOne关系的主题的两倍。我很遗憾地说,因为这使我的问题变得复杂。飞机数据类型如下:

@Entity
public class Aircraft {

    @Id
    private String registration;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "casa_code")
    private Casa casa;

    private String manufacturer;

    private String model;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-d")
    private LocalDate manufacture;

    @ManyToOne(cascade={CascadeType.PERSIST}, fetch = FetchType.EAGER)
    private Client owner;

    @ManyToOne(cascade={CascadeType.PERSIST}, fetch = FetchType.EAGER)
    private Client operator;

    private String base;

    @OneToOne(cascade={CascadeType.ALL})
    @JoinColumn(name = "airframe_id")
    private Airframe airframe;

    @OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
    @JoinColumn(name = "ac_registration")
    private Set<Prop> props;

    @OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
    @JoinColumn(name = "ac_registration")
    private Set<Engine> engines;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-d")
    private LocalDate lastUpdated;

    public Aircraft() {
    }
    // remaining constructors, builders and accessors omitted for brevity

}

可用于保存的控制器方法:

@RestController
@RequestMapping("/api")
public class AircraftController {
    private static final Logger LOG = LoggerFactory.getLogger(AircraftController.class);

    private AircraftService aircraftService;

    @Autowired
    public AircraftController(AircraftService aircraftService) {
        this.aircraftService = aircraftService;
    }

    @Secured("ROLE_ADMIN")
    @PostMapping(value="/maintainers/{mid}/aircrafts", produces = "application/json")
    @ResponseStatus(value = HttpStatus.CREATED)
    Response<Aircraft> create(@PathVariable("mid") Long mid, @RequestBody Aircraft request) {

        return Response.of(aircraftService.create(request));
    }
}

服务方法:

public interface AircraftService {

    Aircraft create(Aircraft aircraft);

    // other interface methods omitted for brevity

    @Service
    class Default implements AircraftService {

        private static final Logger LOG = LoggerFactory.getLogger(AircraftService.class);

        @Autowired
        AircraftRepository aircraftRepository;
        @Transactional
        public Aircraft create(Aircraft aircraft) {
            LOG.debug("creating new Aircraft with {}", aircraft);
            if (aircraft.getOwner() != null && aircraft.getOwner().getNk() == null) {
                aircraft.getOwner().setNk(UUID.randomUUID().toString());
            }
            if (aircraft.getOperator() != null && aircraft.getOperator().getNk() == null) {
                aircraft.getOperator().setNk(UUID.randomUUID().toString());
            }
            return aircraftRepository.save(aircraft);
        }
    }
}

,最后是存储库:

@Repository
public interface AircraftRepository extends JpaRepository<Aircraft, String> {
}

当我提供以下JSON时:

{
  "registration":"VH-ZZZ",
  "casa":null,
  "manufacturer":"PITTS AVIATION ENTERPRISES",
  "model":"S-2B",
  "manufacture":"1983-01-2",
  "owner":{
    "id":null,
    "nk":"84f5f053-82dd-4563-8158-e804b3003f3b",
    "abn":null,
    "name":"xxxxx, xxxxx xxxxxx",
    "principal":null,
    "contact":{
      "id":null,
      "phone":null,
      "address":{
        "id":null,
        "line3":"PO Box xxx",
        "suburb":"KARAMA",
        "postcode":"0813",
        "state":"NT",
        "country":"Australia"
      },
      "email":null
    }
  },
  "operator":{
    "id":null,
    "nk":"edfd3e41-664c-4832-acc5-1c04d9c673a3",
    "abn":null,
    "name":"xxxxx, xxxxx xxxxxx",
    "principal":null,
    "contact":{
      "id":null,
      "phone":null,
      "address":{
        "id":null,
        "line3":"PO Box xxx",
        "suburb":"KARAMA",
        "postcode":"0813",
        "state":"NT",
        "country":"Australia"
      },
      "email":null
    }
  },
  "base":null,
  "airframe":{
    "id":null,
    "acRegistration":null,
    "serialNumber":"5005",
    "hours":null
  },
  "props":[
    {
      "id":null,
      "acRegistration":"VH-ZZZ",
      "engineNumber":1,
      "make":"HARTZELL PROPELLERS",
      "model":"HC-C2YR-4CF/FC8477A-4",
      "casa":null,
      "serialNumber":null,
      "hours":null
    }
  ],
  "engines":[
    {
      "id":null,
      "acRegistration":"VH-ZZZ",
      "engineNumber":1,
      "make":"TEXTRON LYCOMING",
      "model":"AEIO-540",
      "casa":null,
      "serialNumber":null,
      "hours":null
    }
  ],
  "lastUpdated":"2018-12-16"
}

要参加此考试:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("embedded")
@EnableJpaRepositories({ "au.com.avmaint.api" })
@AutoConfigureMockMvc
public class AircraftControllerFunctionalTest {

    private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(),
            Charset.forName("utf8"));

    private HttpMessageConverter mappingJackson2HttpMessageConverter;

    @TestConfiguration
    static class ServiceImplTestContextConfiguration {

        @Bean
        public CasaFixtures casaFixtures() {
            return new CasaFixtures.Default();
        }

        @Bean
        public ModelFixtures modelFixtures() {
            return new ModelFixtures.Default();
        }

        @Bean
        public MaintainerFixtures maintainerFixtures() {
            return new MaintainerFixtures.Default();
        }

        @Bean
        public AircraftFixtures aircraftFixtures() {
            return new AircraftFixtures.Default();
        }
    }

    @Autowired
    private WebApplicationContext context;

    @Autowired
    private MockMvc mvc;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ModelFixtures modelFixtures;

    @Autowired
    private MaintainerFixtures maintainerFixtures;

    @Autowired
    private AircraftFixtures aircraftFixtures;

    Maintainer franks;

    @Autowired
    void setConverters(HttpMessageConverter<?>[] converters) {

        this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream()
                .filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter)
                .findAny()
                .orElse(null);

        assertNotNull("the JSON message converter must not be null",
                this.mappingJackson2HttpMessageConverter);
    }


    @Before
    public void setup() {
        mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity())
                .build();

        franks = maintainerFixtures.createFranksMaintainer();

    }

    @After
    public void tearDown() {

        maintainerFixtures.removeFranks(franks);
        aircraftFixtures.killAircraft(aircrafts);
        UserAndRoleFixtures.killAllUsers(userService, roleService);
    }

    @Test
    public void doCreate() throws Exception {

        File file = ResourceUtils.getFile("classpath:json/request/vh-zzz.json");
        String json = new String(Files.readAllBytes(file.toPath()));

        mvc.perform((post("/api/maintainers/{mid}/aircrafts", franks.getId())
                .header(AUTHORIZATION_HEADER, "Bearer " + ModelFixtures.ROOT_JWT_TOKEN))
                .content(json)
                .contentType(contentType))
                .andDo(print())
                .andExpect(status().isCreated())
                .andExpect(content().contentType(contentType))
                .andExpect(jsonPath("$.payload").isNotEmpty())
                .andExpect(jsonPath("$.payload.registration").value("VH-ZZZ"))
                .andExpect(jsonPath("$.payload.manufacturer").value("PITTS AVIATION ENTERPRISES"))
                .andExpect(jsonPath("$.payload.model").value("S-2B"))
                .andExpect(jsonPath("$.payload.manufacture").value("1983-01-2"))
                .andExpect(jsonPath("$.payload.owner.id").isNotEmpty())
                .andExpect(jsonPath("$.payload.owner.nk").isNotEmpty())
                .andExpect(jsonPath("$.payload.owner.contact").isNotEmpty())
                .andExpect(jsonPath("$.payload.operator.id").isNotEmpty())
                .andExpect(jsonPath("$.payload.operator.nk").isNotEmpty())
                .andExpect(jsonPath("$.payload.operator.contact").isNotEmpty())
        ;
    }

}

我发现飞机中的两个ManyToOne映射是持久的,但OneToOne映射不是。基本上,这两个期望会失败:

.andExpect(jsonPath("$.payload.owner.contact").isNotEmpty())
.andExpect(jsonPath("$.payload.operator.contact").isNotEmpty())

我尝试了一些Cascade选项,例如ALL,MERGE等,看来我的示例与其他示例非常相似。我意识到这有点不寻常,因为“地址”,“人”和“联系人”不包含对父母的引用,但是我会认为这是单向关系的关键。有人知道如何坚持这些吗?

更新-在AircraftService的create方法上,我尝试使用以下方法分别保存所有者和运营商:

@Transactional
public Aircraft create(Aircraft aircraft) {
    if (aircraft.getOwner() != null && aircraft.getOwner().getNk() == null) {
        aircraft.getOwner().setNk(UUID.randomUUID().toString());
    } else if (aircraft.getOwner() != null) {
        if (aircraft.getOwner().getPrincipal() != null) {
            LOG.debug("saving principal");
            Person person = personRepository.save(aircraft.getOwner().getPrincipal());
            aircraft.getOwner().setPrincipal(person);
        }
        if (aircraft.getOwner().getContact() != null) {
            Contact contact = contactRepository.save(aircraft.getOwner().getContact());
            aircraft.getOwner().setContact(contact);
        }
    }
    if (aircraft.getOperator() != null && aircraft.getOperator().getNk() == null) {
        aircraft.getOperator().setNk(UUID.randomUUID().toString());
        if (aircraft.getOperator().getPrincipal() != null) {
            Person person = personRepository.save(aircraft.getOperator().getPrincipal());
            aircraft.getOperator().setPrincipal(person);
        }
        if (aircraft.getOperator().getContact() != null) {
            Contact contact = contactRepository.save(aircraft.getOperator().getContact());
            aircraft.getOperator().setContact(contact);
        }
    }

    return aircraftRepository.save(aircraft);
}

我这样做的前提是,JPA不知道该如何处理对尚不存在的对象的引用。

但没有变化。

除了保存“联系人”和“人员” ID之外,此更改对保存存储库没有任何影响,该存储库仍无法将客户端链接到“联系人”或“人员”。我是否必须将联系人和个人保存在单独的事务中,然后再保存客户?

这是在杀了我:这是怎么回事?

1 个答案:

答案 0 :(得分:0)

问题是我需要在飞机实体上使用CascadeType.MERGE:

@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
private Client owner;

@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
private Client operator;

本质上,当将JSON输入到创建操作中时,它似乎与MERGE操作(与PERSIST不同,在其中创建了一个新实体并将其进行管理)与MERGE操作没有区别,因此MERGE操作被传递给Client而不是PERSIST (正如我期望的那样)。这就是为什么不保留“人”和“联系人”的原因。我仍然不明白为什么JSON输入被当作合并来处理-这没有道理。