为什么第二级嵌套列表上的@NotNull验证在顶级更新时失败?

时间:2019-06-12 18:43:20

标签: spring hibernate jpa spring-data-jpa bean-validation

我有包含联赛,球员和球队的应用程序。该应用程序允许客户与团队和这些团队中的球员建立联赛。

稍后,客户可以通过添加新的球员团队来修改联赛。到那时,客户端从我的应用程序收到意外的验证错误。该错误表明即使客户已明确发送了属于新团队的新球员列表,新球员列表也不能为空。

以下是实体:

@Entity
@Data
public class League {

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

    private String name;

    @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
    @JoinColumn(name="leagueId", nullable=false)
    @Valid
    @NotNull
    private List<Team> teams;
}

@Entity
@Data
public class Team {

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

    private String name;

    @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
    @JoinColumn(name="teamId", nullable=false)
    @Valid
    @NotNull
    private List<Player> players;
}

@Entity
@Data
public class Player {

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

    private String name;    
}

这是我的集成测试,可以重现该问题:

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class LeagueSaveTest {

    @Autowired
    private LeagueRepository repo;

    @Test
    public void updateLegaue() {

        Player ramsey = new Player();
        ramsey.setId(1L);
        ramsey.setName("Aaron Ramsey");

        Team arsenal = new Team();
        arsenal.setId(1L);
        arsenal.setName("Arsenal");
        arsenal.setPlayers(Arrays.asList(ramsey));

        Player hazard = new Player();
        hazard.setName("Eden Hazard");

        Team chelsea = new Team();
        chelsea.setName("Chelsea");
        chelsea.setPlayers(Arrays.asList(hazard));

        League premier = new League();
        premier.setId(1L);
        premier.setName("Premier");
        premier.setTeams(Arrays.asList(arsenal, chelsea));

        repo.save(premier);
    }   
}

这是我得到的验证错误:

INFO 16136 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@557caf28 testClass = LeagueSaveTest, testInstance = com.example.service.LeagueSaveTest@133d0471, testMethod = updateLegaue@LeagueSaveTest, testException = javax.validation.ConstraintViolationException: Validation failed for classes [com.example.domain.Team] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=players, rootBeanClass=class com.example.domain.Team, messageTemplate='{javax.validation.constraints.NotNull.message}'}
], mergedContextConfiguration = [WebMergedContextConfiguration@408d971b testClass = LeagueSaveTest, locations = '{}', classes = '{class com.example.LeagueApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@371a67ec, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@1a3869f4, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@63440df3, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@569cfc36], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]]

为什么即使所有团队都有至少一名球员,我也遇到此验证错误?

1 个答案:

答案 0 :(得分:0)

在Team类中,您声明“ id”是自动生成概念。但是您将值分配为常量。只有它会引发错误。

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class LeagueSaveTest {

@Autowired
private LeagueRepository repo;

@Test
public void updateLeague() {

    Player ramsey = new Player();
    ramsey.setName("Aaron Ramsey");

    Team arsenal = new Team();
    arsenal.setName("Arsenal");
    arsenal.setPlayers(Arrays.asList(ramsey));

    Player hazard = new Player();
    hazard.setName("Eden Hazard");

    Team chelsea = new Team();
    chelsea.setName("Chelsea");
    chelsea.setPlayers(Arrays.asList(hazard));

    League premier = new League()
    premier.setName("Premier");
    premier.setTeams(Arrays.asList(arsenal, chelsea));

    repo.save(premier);
}   

}