简体   繁体   中英

OneToMany mapping generates the wrong hibernate SQL during findById/findAll

I cannot get the below OneToMany mappings to work properly, even though they are supposedly validated (by hibernate.ddl-auto=validate). I can insert all entities in the application with no problems, but while doing a findAll or findById, the queries Hibernate generates for me are wrong and result in exceptions. This is very likely due to a problem with my OneToMany mappings, or lack of a ManyToOne mapping but I don't see how to make it work.

Currently, the following tables exist in my postgres12 database:

CREATE TABLE battlegroups (
    id uuid,
    gameworld_id uuid,
    name varchar(255),
    PRIMARY KEY(id)
);

CREATE TABLE battlegroup_players (
    id uuid,
    battlegroup_id uuid,
    player_id integer,
    name varchar(255),
    tribe varchar(255),
    PRIMARY KEY (id)
);

CREATE TABLE battlegroup_player_villages(
    battlegroup_id uuid,
    player_id integer,
    village_id integer,
    x integer,
    y integer,
    village_name varchar(255),
    tribe varchar(255),
    PRIMARY KEY(battlegroup_id, player_id, village_id, x, y)
);

These are mapped to the following entities in Kotlin:

@Entity
@Table(name = "battlegroups")
class BattlegroupEntity(
                        @Id
                        val id: UUID,
                        @Column(name = "gameworld_id")
                        val gameworldId: UUID,
                        val name: String? = "",
                        @OneToMany(mappedBy = "battlegroupId", cascade = [CascadeType.ALL],fetch = FetchType.EAGER)
                        private val players: MutableList<BattlegroupPlayerEntity>) 

@Entity
@Table(name = "battlegroup_players")
class BattlegroupPlayerEntity(@Id
                              val id: UUID,
                              @Column(name = "battlegroup_id")
                              val battlegroupId: UUID,
                              @Column(name = "player_id")
                              val playerId: Int,
                              val name: String,
                              @Enumerated(EnumType.STRING)
                              val tribe: Tribe,
                              @OneToMany(mappedBy= "id.playerId" , cascade = [CascadeType.ALL], fetch = FetchType.EAGER)
                              val battlegroupPlayerVillages: MutableList<BattlegroupPlayerVillageEntity>) 

@Entity
@Table(name = "battlegroup_player_villages")
class BattlegroupPlayerVillageEntity(
        @EmbeddedId
        val id: BattlegroupPlayerVillageId,
        @Column(name ="village_name")
        val villageName: String,
        @Enumerated(EnumType.STRING)
        val tribe: Tribe) 

@Embeddable
data class BattlegroupPlayerVillageId(
        @Column(name = "battlegroup_id")
        val battlegroupId: UUID,
        @Column(name = "player_id")
        val playerId: Int,
        @Column(name = "village_id")
        val villageId: Int,
        val x: Int,
        val y: Int
): Serializable

This is the SQL hibernate generates when I do a findAll/findById on a battlegroup:

 select
        battlegrou0_.id as id1_2_0_,
        battlegrou0_.gameworld_id as gameworl2_2_0_,
        battlegrou0_.name as name3_2_0_,
        players1_.battlegroup_id as battlegr2_1_1_,
        players1_.id as id1_1_1_,
        players1_.id as id1_1_2_,
        players1_.battlegroup_id as battlegr2_1_2_,
        players1_.name as name3_1_2_,
        players1_.player_id as player_i4_1_2_,
        players1_.tribe as tribe5_1_2_,
        battlegrou2_.player_id as player_i2_0_3_,
        battlegrou2_.battlegroup_id as battlegr1_0_3_,
        battlegrou2_.village_id as village_3_0_3_,
        battlegrou2_.x as x4_0_3_,
        battlegrou2_.y as y5_0_3_,
        battlegrou2_.battlegroup_id as battlegr1_0_4_,
        battlegrou2_.player_id as player_i2_0_4_,
        battlegrou2_.village_id as village_3_0_4_,
        battlegrou2_.x as x4_0_4_,
        battlegrou2_.y as y5_0_4_,
        battlegrou2_.tribe as tribe6_0_4_,
        battlegrou2_.village_name as village_7_0_4_ 
    from
        battlegroups battlegrou0_ 
    left outer join
        battlegroup_players players1_ 
            on battlegrou0_.id=players1_.battlegroup_id 
    left outer join
        battlegroup_player_villages battlegrou2_ 
            on players1_.id=battlegrou2_.player_id -- ERROR: comparing integer to uuid
    where
        battlegrou0_.id=?

This results in an exception:

PSQLException: ERROR: operator does not exist: integer = uuid

Which makes perfect sense, since it is comparing the battlegroup_players id, which is a uuid, to the battlegroup_player_villages player_id, which is an integer. It should instead be comparing/joining on the battlegroup_player's player_id to the battlegroup_player_village's player_id.

If I change the sql to reflect that and manually execute the above query with the error line replaced:

   on players1_.player_id=battlegrou2_.player_id 

I get exactly the results I want. How can I change the OneToMany mappings so that it does exactly that? Is it possible to do this without having a BattlegroupPlayerEntity object in my BattlegroupPlayerVillageEntity class?

Bonus points if you can get the left outer joins to become regular inner joins.

EDIT:

I tried the current answer, had to slightly adjust my embedded id because my code could not compile otherwise, should be the same thing:

@Embeddable
data class BattlegroupPlayerVillageId(
        @Column(name = "battlegroup_id")
        val battlegroupId: UUID,
        @Column(name = "village_id")
        val villageId: Int,
        val x: Int,
        val y: Int
): Serializable {
    @ManyToOne
    @JoinColumn(name = "player_id")
    var player: BattlegroupPlayerEntity? = null
}

Using this still results in a comparison between int and uuid, for some reason.

Schema-validation: wrong column type encountered in column [player_id] in table [battlegroup_player_villages]; found [int4 (Types#INTEGER)], but expecting [uuid (Types#OTHER)]

Interestingly, if I try to put a referencedColumnName = "player_id" in there, I get a stackoverflow error instead.

I did some digging and found some issues with the mapping as well as classes, I will try to explain as much as possible.

WARNING!!! TL;DR

I will use Java for code, I hope that should not be a problem converting to kotlin.

There are some issues with classes also(hint: Serializable), so classes must implements Serializable.

Used lombok to reduce the boilerplate

Here is the changed BattleGroupPlayer entity:

@Entity
@Getter
@NoArgsConstructor
@Table(name = "battle_group")
public class BattleGroup implements Serializable {
    private static final long serialVersionUID = 6396336405158170608L;

    @Id
    private UUID id;

    private String name;

    @OneToMany(mappedBy = "battleGroupId", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<BattleGroupPlayer> players = new ArrayList();

    public BattleGroup(UUID id, String name) {
        this.id = id;
        this.name = name;
    }

    public void addPlayer(BattleGroupPlayer player) {
        players.add(player);
    }
}

and BattleGroupVillage and BattleGroupVillageId entity

@AllArgsConstructor
@Entity
@Getter
@NoArgsConstructor
@Table(name = "battle_group_village")
public class BattleGroupVillage implements Serializable {
    private static final long serialVersionUID = -4928557296423893476L;

    @EmbeddedId
    private BattleGroupVillageId id;

    private String name;
}


@Embeddable
@EqualsAndHashCode
@Getter
@NoArgsConstructor
public class BattleGroupVillageId implements Serializable {
    private static final long serialVersionUID = -6375405007868923427L;

    @Column(name = "battle_group_id")
    private UUID battleGroupId;

    @Column(name = "player_id")
    private Integer playerId;

    @Column(name = "village_id")
    private Integer villageId;

    public BattleGroupVillageId(UUID battleGroupId, Integer playerId, Integer villageId) {
        this.battleGroupId = battleGroupId;
        this.villageId = villageId;
        this.playerId = playerId;
    }
}

Now, Serializable needs to be implemented in every class as we have used @EmbeddedId which requires the container class to be Serializable as well, hence every parent class must implement serializable, otherwise it would give error.

Now, we can solve the problem using @JoinColumn annotation like below:

@OneToMany(cascade = CasacadeType.ALL, fetch =EAGER)
@JoinColumn(name = "player_id", referencedColumnName = "player_id")
private List<BattleGroupVillage> villages = new ArrayList<>();

name -> field in child table and referenceColumnName -> field in parent table.

This will join the column player_id column in both entities.

SELECT 
    battlegrou0_.id AS id1_0_0_,
    battlegrou0_.name AS name2_0_0_,
    players1_.battle_group_id AS battle_g2_1_1_,
    players1_.id AS id1_1_1_,
    players1_.id AS id1_1_2_,
    players1_.battle_group_id AS battle_g2_1_2_,
    players1_.player_id AS player_i3_1_2_,
    villages2_.player_id AS player_i4_2_3_,
    villages2_.battle_group_id AS battle_g1_2_3_,
    villages2_.village_id AS village_2_2_3_,
    villages2_.battle_group_id AS battle_g1_2_4_,
    villages2_.player_id AS player_i4_2_4_,
    villages2_.village_id AS village_2_2_4_,
    villages2_.name AS name3_2_4_
FROM
    battle_group battlegrou0_
        LEFT OUTER JOIN
    battle_group_player players1_ ON battlegrou0_.id = players1_.battle_group_id
        LEFT OUTER JOIN
    battle_group_village villages2_ ON players1_.player_id = villages2_.player_id
WHERE
    battlegrou0_.id = 1;

But this would give 2 players if you check the BattleGroup#getPlayers() method, below is the test case to verify.

UUID battleGroupId = UUID.randomUUID();

        doInTransaction( em -> {
            BattleGroupPlayer player = new BattleGroupPlayer(UUID.randomUUID(), battleGroupId, 1);

            BattleGroupVillageId villageId1 = new BattleGroupVillageId(
                    battleGroupId,
                    1,
                    1
            );
            BattleGroupVillageId villageId2 = new BattleGroupVillageId(
                    battleGroupId,
                    1,
                    2
            );

            BattleGroupVillage village1 = new BattleGroupVillage(villageId1, "Village 1");
            BattleGroupVillage village2 = new BattleGroupVillage(villageId2, "Village 2");

            player.addVillage(village1);
            player.addVillage(village2);

            BattleGroup battleGroup = new BattleGroup(battleGroupId, "Takeshi Castle");
            battleGroup.addPlayer(player);

            em.persist(battleGroup);

        });

        doInTransaction( em -> {
            BattleGroup battleGroup = em.find(BattleGroup.class, battleGroupId);

            assertNotNull(battleGroup);
            assertEquals(2, battleGroup.getPlayers().size());

            BattleGroupPlayer player = battleGroup.getPlayers().get(0);
            assertEquals(2, player.getVillages().size());
        });

If your use case was to get the single player from BattleGroup then you would have to use FETCH.LAZY , which is btw good for performance as well.

Why LAZY works?

Because LAZY loading will issue separate select statement when you really access them. EAGER will load whole graph, wherever you have it. It means, it will try to load all relationship mapped with this type, hence it will perform outer join (which may result in 2 rows for players as your criteria is unique because of villageId, which you cannot know before querying).

If you have more than 1 such fields ie want join on battleGroupId as well, you would need this

@JoinColumns({
                    @JoinColumn(name = "player_id", referencedColumnName = "player_id"),
                    @JoinColumn(name = "battle_group_id", referencedColumnName = "battle_group_id")
            }
    )

NOTE: Used h2 in memory db for test case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM