0

我有以下情况,一篇文章可以有几种类型的内容(例如Text,Images,Sourcecode,...)。因此我设计了这个简单的类结构:

这是抽象ArticleContent类的来源:

@Entity
@Table( name = "ARTICLE_CONTENTS" )
@Inheritance( strategy = InheritanceType.TABLE_PER_CLASS )
public abstract class ArticleContent extends AbstractEntity {

  private Article article;

  @ManyToOne
  @JoinColumn( name = "ARTICLE_ID", nullable = false, updatable = false )
  public Article getArticle() {
    return article;
  }

  public void setArticle( Article article ) {
    this.article = article;
  }

  @Column( name = "CONTENT", columnDefinition = "TEXT", nullable = false )
  public abstract String getContent();

  public abstract void setContent( String content );

}

getContent()andsetContent()方法被标记为抽象,因为它们将返回实际显示的内容(例如纯文本、<img src="..." />...)。

我从TextArticleContent类的实现开始。这个类只是将内容存储在一个字符串中:

@Entity
@Table( name = "TEXT_ARTICLE_CONTENTS" )
@AttributeOverrides( { @AttributeOverride( name = "content", column = @Column( name = "CONTENT" ) ) } )
public class TextArticleContent extends ArticleContent {

  private String content;

  @Override
  public String getContent() {
    return content;
  }

  @Override
  public void setContent( String content ) {
    this.content = content;
  }

}

这是我收到的错误输出:

Caused by: org.hibernate.MappingException:
Repeated column in mapping for entity: com.something.model.TextArticleContent column: 
  CONTENT (should be mapped with insert="false" update="false")

尽管错误消息给了我一个建议(should be mapped with insert="false" update="false"),但老实说,当我刚开始使用 Hibernate 时,我不知道如何处理它。

更新:解决 方案这个问题的解决方案是我需要更改方法的@Column注释getContent()。正确的注释如下所示:

@Column( name = "CONTENT", columnDefinition = "TEXT", nullable = false, insertable = false, updatable = false )
public abstract String getContent();

我不得不添加insertableupdatable,这基本上意味着 Exception 中的提示并不完全正确。

此外,我需要更改抽象ArticleContent类的 InheritanceStrategy。正确的@Inheritance注释是:

@Inheritance( strategy = InheritanceType.SINGLE_TABLE )

出于美观的原因,现在可以将TextArticleContent@Table类中的注释替换为:

@DiscriminatorValue( "TEXT_ARTICLE_CONTENT" )

这会将ARTICLE_CONTENTS表中的鉴别器值更改为TEXT_ARTICLE_CONTENT

4

1 回答 1

1

尝试更改 ArticleContent

    @Column( name = "CONTENT", columnDefinition = "TEXT", nullable = false )
  public abstract String getContent();

        @Column( name = "CONTENT", columnDefinition = "TEXT", nullable = false,
insertable = false, updatable = false )
      public abstract String getContent();

更新

改为可插入、可更新。

于 2013-03-24T13:02:17.117 回答