Hibernate 6 Wrong query generated with @DiscriminatorValue

I created this repo to highlight the issue with spring boot 3 / Hibernate 6.1.5 : GitHub - gaetannandelec-ibboost/hibernate6-discriminatorbug

I have the following classes

    @Entity
    @Table(name = "users")
    public class User extends BaseEntity implements Serializable {
    
    ..
    
    	@OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.MERGE, CascadeType.PERSIST }, mappedBy = "entity")
    	private Set<UserUdfValue> properties = new HashSet<>();
    
    ..
    
    }

    @Entity
    @DiscriminatorValue(UserUdfValue.UDFID)
    public class UserUdfValue extends ValueBase {
    
    	private static final long serialVersionUID = -898152830344556386L;
    
    	public final static String UDFID = "1";
    
    	@ManyToOne(fetch=FetchType.LAZY, cascade = {})
    	@JoinColumn(name = "entity_id", nullable = false)
    	private User entity;
    
    	public User getEntity() {
    		return entity;
    	}
    
    	public void setEntity(User entity) {
    		this.entity = entity;
    	}
    
    }


    @Entity(name = "udf_value")
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name = "target_type", discriminatorType = DiscriminatorType.INTEGER)
    @DiscriminatorOptions(force = false)
    public abstract class ValueBase implements Serializable {
    	private static final long serialVersionUID = 1L;
    
    	@Id
    	@GeneratedValue(strategy = GenerationType.AUTO)
    	private Long id;
    	
    ...
    
    }

Prior migrating to hibernate 6 ( hibernate 5.6 ), when querying a user by id , it was generating an sql query like i expect

    SELECT *
    FROM users user0_
    LEFT OUTER JOIN udf_value properties14_ ON user0_.id = properties14_.entity_id
        AND properties14_.target_type = 1
    WHERE user0_.id = ?

However with hibernate 6 the discriminator criteria is no longer on the join but in the where clause

    SELECT *
    FROM users u1_0
    LEFT JOIN udf_value p2_0 ON u1_0.id = p2_0.entity_id
    WHERE p2_0.target_type = 1
        AND u1_0.id = ?

Which obviously doesn’t give me the same result i expect

1 Like

Yep, that’s a bug. Thanks for reporting it! Please create an issue in the issue tracker(https://hibernate.atlassian.net) and in there refer to this discourse topic and the GitHub repository you created.

1 Like

Thank you, i created a ticket for it [HHH-15829] - Hibernate JIRA

1 Like

We are in the process of upgrading to version 6. Our datamodel is relying heavily on entities with discriminator colum and quries containing left joins are broken. Rewriting all queries is no option.

Is there any workaround for this problem, apart from waiting or stopping the upgrade?

No workaround. You’ll have to wait for the fix.

1 Like