简体   繁体   English

JPA 单表 inheritance 映射和到子类的两个关系失败并出现意外结果(Hibernate)

[英]JPA single-table inheritance mapping and two relationships to sub classes fails with unexpected result (Hibernate )

We have a simple single table mapping, a ship with images and documents (both sub classes of an attachment) attached to it:我们有一个简单的单表映射,一艘附有图像和文档(附件的子类)的船:

@Entity
@Table(name = "SHIPS")
public class Ship implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "ID")
    private Long id;

    @Basic(optional = false)
    @Column(name = "NAME")
    private String name;

    @OneToMany(mappedBy = "ship", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    // @Where(clause = "DISCR = 'I'")
    private List<Image> images = new ArrayList<>();

    @OneToMany(mappedBy = "ship", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    // @Where(clause = "DISCR = 'D'")
    private List<Document> documents = new ArrayList<>();

    public Ship() {}

    public Ship(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Image> getImages() {
        return images;
    }

    public void setImages(List<Image> images) {
        this.images = images;
    }

    public List<Document> getDocuments() {
        return documents;
    }

    public void setDocuments(List<Document> documents) {
        this.documents = documents;
    }
}
@Entity
@Table(name = "ATTACHMENTS")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "DISCR")
public abstract class BaseAttachment implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "ID")
    protected Long id;

    @Basic(optional = false)
    @Column(name = "DISCR", insertable = false, updatable = false)
    protected String discr;

    @Basic(optional = false)
    @Column(name = "FILE_NAME")
    protected String fileName;

//  @Lob
//  @Basic(optional = false)
//  @Column(name = "ORIGINAL_DATA")
//  protected byte[] originalData;

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "SHIP_ID", referencedColumnName = "ID")
    protected Ship ship;

    public BaseAttachment() {}

    public BaseAttachment(Long id, String fileName) {
        this.id = id;
        this.fileName = fileName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDiscr() {
        return discr;
    }

    public void setDiscr(String discr) {
        this.discr = discr;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

//  public byte[] getOriginalData() {
//      return originalData;
//  }
//
//  public void setOriginalData(byte[] originalData) {
//      this.originalData = originalData;
//  }

    public Ship getShip() {
        return ship;
    }

    public void setShip(Ship ship) {
        this.ship = ship;
    }
}
@Entity
@DiscriminatorValue("I")
public class Image extends BaseAttachment {

    private static final long serialVersionUID = 1L;

    @Column(name = "ALTERNATIVE_TEXT")
    private String alternativeText;

    public Image() {}

    public Image(Long id, String fileName) {
        super(id, fileName);
    }

    public String getAlternativeText() {
        return alternativeText;
    }

    public void setAlternativeText(String alternativeText) {
        this.alternativeText = alternativeText;
    }
}
@Entity
@DiscriminatorValue("D")
public class Document extends BaseAttachment {

    private static final long serialVersionUID = 1L;

    public Document() {}

    public Document(Long id, String fileName) {
        super(id, fileName);
    }
}

I created a test case for Hibernate:我为 Hibernate 创建了一个测试用例:

@TestForIssue( jiraKey = "HHH-99999")
public class TwoRelationshipsToSubclassTest extends BaseEntityManagerFunctionalTestCase {

    @Override
    public Class<?>[] getAnnotatedClasses() {
        return new Class<?>[]{Ship.class, BaseAttachment.class, Image.class, Document.class};
    }

    @Override
    protected void addConfigOptions(Map options) {
        options.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, "false" );
        options.put( AvailableSettings.SHOW_SQL, "true" );
        options.put( AvailableSettings.FORMAT_SQL, "true" );
        options.put( AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, "true" );
    }

    @Before
    public void prepare() {
        doInJPA( this::entityManagerFactory, em -> {
            Ship ship = new Ship(1L, "Titanic");
            // images
            Image image1 = new Image(1L, "abc.png");
            image1.setShip(ship);
            Image image2 = new Image(2L, "def.jpg");
            image2.setShip(ship);
            // documents
            Document document1 = new Document(3L, "ghi.docx");
            document1.setShip(ship);
            Document document2 = new Document(4L, "jkl.pdf");
            document2.setShip(ship);
            Document document3 = new Document(5L, "mno.txt");
            document3.setShip(ship);
            // images relationship
            ship.getImages().add(image1);
            ship.getImages().add(image2);
            // documents relationship
            ship.getDocuments().add(document1);
            ship.getDocuments().add(document2);
            ship.getDocuments().add(document3);
            // persist
            em.persist( ship );
        });
    }

    /**
     * Use --debug to see the SQL being run + the sysouts.
     */
    @Test
    public void test() {
        doInJPA( this::entityManagerFactory, em -> {
            Ship ship = em.find( Ship.class, 1L );
            Assert.assertNotNull("Ship not found!", ship);
            List<Image> images = ship.getImages();
            Assert.assertEquals(2, images.size());
            List<Document> documents = ship.getDocuments();
            Assert.assertEquals(3, documents.size());
        } );
    }
}

Fails with:失败:


expected:<2> but was:<5>
Expected :2
Actual   :5
<Click to see difference>

java.lang.AssertionError: expected:<2> but was:<5>
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:834)
    at org.junit.Assert.assertEquals(Assert.java:645)
    at org.junit.Assert.assertEquals(Assert.java:631)
    at org.hibernate.jpa.test.inheritance.singletable.TwoRelationshipsToSubclassTest.lambda$test$3(TwoRelationshipsToSubclassTest.java:68)
    at org.hibernate.testing.transaction.TransactionUtil.doInJPA(TransactionUtil.java:206)
    at org.hibernate.testing.transaction.TransactionUtil.doInJPA(TransactionUtil.java:247)
    at org.hibernate.jpa.test.inheritance.singletable.TwoRelationshipsToSubclassTest.test(TwoRelationshipsToSubclassTest.java:64)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.hibernate.testing.junit4.ExtendedFrameworkMethod.invokeExplosively(ExtendedFrameworkMethod.java:45)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:298)
    at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.lang.Thread.run(Thread.java:832)


org.hibernate.jpa.test.inheritance.singletable.TwoRelationshipsToSubclassTest > test FAILED
    java.lang.AssertionError at TwoRelationshipsToSubclassTest.java:68
1 test completed, 1 failed
> Task :hibernate-core:test FAILED
> Task :hibernate-core:buildDashboard UP-TO-DATE
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':hibernate-core:test'.
> There were failing tests. See the report at: file:///C:/projects/hibernate-orm/hibernate-core/target/reports/tests/test/index.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org

What happens here is that the subclass instances for ALL types are fetched (size 5), which is wrong (should be 2 images and 3 documents).这里发生的是获取所有类型的子类实例(大小 5),这是错误的(应该是 2 个图像和 3 个文档)。

This test fails with all Hibernate 5.x branches, 5.3, 5.4, 5.5 and 5.6.此测试在所有 Hibernate 5.x 分支、5.3、5.4、5.5 和 5.6 中均失败。 On Hibernate 6.0.0.RC1 this test is working fine (as my expectation would be).在 Hibernate 6.0.0.RC1 上,此测试运行良好(如我所料)。

QUESTION(S):问题):

Is this supposed to work according to the JPA spec?这应该根据 JPA 规范工作吗? Is this a bug in Hibernate 5.x then?那么这是 Hibernate 5.x 中的错误吗?

Does anyone happen to know which issue HHH-?????有谁碰巧知道哪个问题 HHH-?????? fixed this for Hibernate 6.x?为 Hibernate 6.x 修复了这个?

Note: we currently have to add proprietary @Where(clause = "DISCR = 'D'") and @Where(clause = "DISCR = 'I'") to get around this.注意:我们目前必须添加专有@Where(clause = "DISCR = 'D'")@Where(clause = "DISCR = 'I'")来解决这个问题。

It's a bug in all Hibernate 5.x versions.这是所有 Hibernate 5.x 版本中的错误。

I don't know which HHH fixed this or if we even tagged a commit properly.我不知道是哪个 HHH 解决了这个问题,也不知道我们是否正确标记了提交。 We just figured that this was wrong in Hibernate 5.x so we fixed it at some point.我们只是认为这在 Hibernate 5.x 中是错误的,所以我们在某个时候修复了它。

See here:看这里:

https://discourse.hibernate.org/t/two-relationships-to-single-table-inheritance-sub-classes-failing-with-hibernate-5-3/6012 https://discourse.hibernate.org/t/two-relationships-to-single-table-inheritance-sub-classes-failing-with-hibernate-5-3/6012

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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