1

我正在尝试 Spring Data JDBC,我认为不可变实体是这里的关键特性。

我想为团队和玩家之间的一对多关系建模,并使这些实体不可变。我现在的工作是:

@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Team {
  @Id
  @Wither
  private Integer id;

  private String name;
  private List<Player> players;
}
@Value
public class Player {
  @Id
  @Wither
  Integer id;
  String name;
  public static Player of(String name) {
    return new Player(null, name);
  }
}

我设法让 OneToMany 关系为可变类正常工作。我设法使它适用于不可变的 Player。@NoArgsConstructor但是,如果没有或@Value代替我现在拥有的东西,我无法让团队映射工作。当缺少此构造函数时,我收到奇怪的消息,好像 Spring Data JDBC 开始看到不同的映射:

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Column "players_id" not found [42122-199]

如果有人尝试重新创建该场景,这是我的 h2 架构:

create table team (id serial primary key, name varchar);
create table player (id serial primary key, name varchar, team int references team(id), team_key int);

还有我的 Spock 测试:

@SpringBootTest
class TeamRepositoryTest extends Specification {
    @Autowired
    TeamRepository teamRepository

    def "Context loads"() {
        given:
        def rick = Player.of("Rick")
        def morty = Player.of("Morty")
        def team = new Team(null, "Rick and Morty", Arrays.asList(rick, morty))

        when:
        def savedTeam = teamRepository.save(team)

        then:
        def savedTeamOpt = teamRepository.findById(savedTeam.id)
        Team retrievedTeam = savedTeamOpt.get()
        retrievedTeam.id == savedTeam.id
        retrievedTeam.name == "Rick and Morty"
        retrievedTeam.players.size() == 2
    }
}

4

1 回答 1

1

您在 Spring Data JDBC 中遇到了一个错误:https ://jira.spring.io/browse/DATAJDBC-127

当前实体或实体集合不能用作构造函数参数。创建一个没有这些参数的构造函数并添加 setter,或者如果你想为它们保持不可变的凋谢

于 2019-06-10T13:35:25.057 回答