SpringData JPA测试中具有EmbeddedId的OneToMany返回null

时间:2019-03-31 22:11:43

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

我有表carseason_tickers,我想通过关系ManyToMany将它们联接起来,联接表应该有额外的字段。完成代码后,我决定通过@DataJpaTest进行测试(我使用SpringBootSpring Data JPA)。根据此测试,我发现代码无法正常工作,原因是OneToMany字段返回null(请参见失败的断言下测试代码中的注释)。你能帮我解决吗?

PS:我在生产代码上对其进行了测试,并且一切正常。因此,问题仅在@DataJpaTest

我的测试具有以下视图:

@ExtendWith({SpringExtension.class})
@DataJpaTest
public class CarDaoTest {

@Autowired
private TestEntityManager testEntityManager;

@Autowired
private CarDAO carDAO;

@Test
void findCarWithSeasonTicketTest(){
    SeasonTicket seasonTicket = SeasonTicket.builder()
            .name("TestName")
            .build();
    seasonTicket = testEntityManager.persist(seasonTicket);

    Car car = Car.builder()
            .carNumber("someCarNumber")
            .build();
    car = testEntityManager.persist(car);

    CarSeasonTicket carSeasonTicket = CarSeasonTicket.builder()
            .car(car)
            .seasonTicket(seasonTicket)
            .startDate(LocalDateTime.now())
            .endDate(LocalDateTime.now())
            .build();

    carSeasonTicket = testEntityManager.persist(carSeasonTicket);

    Optional<Car> findCar = carDAO.findById(car.getId());
    assertThat(findCar.isPresent()).isTrue();

    Car carFromDAO = findCar.get();

    // test fails in this line with message Expecting actual not to be null
    assertThat(carFromDAO.getSeasonTickets()).hasSize(1);
}

}

汽车实体:

@Entity
@Table(name = "cars")
public class Car {

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

@Column(name="car_number", nullable = false, length = 10)
private String carNumber;

@OneToMany(mappedBy = "car", fetch = FetchType.EAGER)
private List<CarSeasonTicket> seasonTickets;
}

已加入表格实体:

@Entity
@Table(name = "car_season_ticket")
@Data
public class CarSeasonTicket {

@EmbeddedId
@Builder.Default private CarSeasonTicketId carSeasonTicketId = new CarSeasonTicketId();

@ManyToOne(fetch = FetchType.LAZY)
@MapsId("carId")
private Car car;

@ManyToOne(fetch = FetchType.LAZY)
@MapsId("seasonTicketId")
private SeasonTicket seasonTicket;

@Column(name = "start_date")
private LocalDateTime startDate;

@Column(name = "end_date")
private LocalDateTime endDate;
}

可嵌入密钥:

@Embeddable
@Data
public class CarSeasonTicketId implements Serializable {

@Column(name = "car_id")
private Long carId;

@Column(name = "season_ticket_id")
private Long seasonTicketId;
}

0 个答案:

没有答案