Sorry for my poor English. There are 3 objects: PostTable, Post and Category. Post and Category both extends PostTable . PostTable represents the data table named "cp_table". The "type" field is the DiscriminatorColumn of table, data type is integer. The Category entity's DiscriminatorValue is "1", the Post's is "2". The code outlines of them as below:
@Entity
@Table(name = "cp_post")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.INTEGER)
public class PostTable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
protected String title;
protected String alias;
protected String keyword;
protected String summary;
protected String author;
protected String source;
protected Date updateTime;
protected String content;
protected Integer hits;
protected Integer postOrder;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false)
protected User user;
protected Date addTime;
protected Integer status;
protected String image;
}
@Entity
@DiscriminatorValue("1")
public class Category extends PostTable {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
protected Category category;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "category")
@OrderBy("postOrder ASC")
protected List<Category> children;
}
@Entity
@DiscriminatorValue("2")
public class Post extends PostTable {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
protected Category category;
}
However, when I invoke Category Entity's getChildren() method to gain the associated Collection of Category, I found that the collection contains the Post entity ( which's type = "2") unexpectedly ! The java code as blow:
Category category = hibernateDao.get(Category.class, 7);
List<Category> children = category.getChildren();
for (Category child : children) {
System.out.println(child.getId());
}
The corresponding SQL statement as blow: " SELECT children0_.category_id AS categor17_38_1_, children0_.id AS id2_38_1_, children0_.id AS id2_38_0_, children0_.add_time AS add_time3_38_0_, children0_.alias AS alias4_38_0_, children0_.author AS author5_38_0_, children0_.content AS content6_38_0_, children0_.hits AS hits7_38_0_, children0_.image AS image8_38_0_, children0_.keyword AS keyword9_38_0_, children0_.post_order AS post_or10_38_0_, children0_.source AS source11_38_0_, children0_. STATUS AS status12_38_0_, children0_.summary AS summary13_38_0_, children0_.title AS title14_38_0_, children0_.update_time AS update_15_38_0_, children0_.user_id AS user_id16_38_0_, children0_.category_id AS categor17_38_0_ FROM cp_post children0_ WHERE children0_.category_id =? ORDER BY children0_.post_order ASC " However, the expected query should add type restriction. e.g. " AND children0_.type = 1" . Because the definition of Category entity is "type = 1", it should be treated strictly in anywhere. Additionally. the Hibernate version I'm using is 5.2.6 Final. I've no enough time to test for each version. Best wishes. |