Hibernate继承,Collections和@OrderedBy超类属性生成MySQL语法错误

时间:2011-03-22 15:22:17

标签: java mysql hibernate inheritance

我使用Hibernate 3.6.1来映射三个实体

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Entry {
   private Long id; 
   private Date publishedAt; 

   @Id
   public getId() {...}

   ...
}

@Entity
public class Category {
   private Long id; 

   List<Podcast> podcasts;

   @Id
   public getId() {...}

   @OneToMany(mappedBy = "category", cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
   @OrderBy("publishedAt")
   public List<Podcast> getPodcasts() {
      return podcasts;
   }
}

@Entity
public class Podcast extends Entry {

   private Category category; 

   @ManyToOne(fetch = FetchType.EAGER)
   public PodcastsCategory getCategory() {
      return category;
   }
}

如果我尝试获取Category实例,我会收到异常

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'podcasts0_.Entry.publishedAt' in 'order clause'

导致此例外的原因是什么?这个映射有什么问题吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试注释@MappedSuperClass。请参阅hibernate文档的2.2.4.4. Inherit properties from superclasses部分。

答案 1 :(得分:1)

这是由以下错误引起的:HHH-3577 Wrong SQL in order by clause when using joined subclasses

作为一种变通方法,您可以删除@OrderBy上的fetch = FetchType.EAGERpodcasts并使用以下查询而不是get()加载类别:

SELECT DISTINCT c 
FROM Category c LEFT JOIN FETCH c.podcasts p
WHERE c.id = ?
ORDER BY p.publishedAt