我正在尝试 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
}
}