Hibernate @ManyToOne与@JoinTable和继承的关系

时间:2013-01-23 14:11:40

标签: hibernate inheritance jointable

[Hibernate - 4.1.9.Final] [MySQL驱动程序]

嗨,我有以下实体。

ANIMAL:

@Entity
@Table( name = "ANIMAL" )
@Inheritance( strategy = InheritanceType.TABLE_PER_CLASS )
public abstract class Animal implements Serializable
{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue( strategy = GenerationType.TABLE )
@Column( name = "ANIMAL_ID" )
public Long id;

@Column( name = "ANIMAL_NAME" )
public String name;

}

狗:

@Entity
@Table( name = "DOG" )
public class Dog extends Animal implements Cloneable, Serializable
{
private static final long serialVersionUID = 1L;

@ManyToOne
@JoinTable( name = "DOG_OTHER_DOG" )
public Dog dog;

}

在Dog实体上有循环关系。

 @ManyToOne
 @JoinTable( name = "DOG_OTHER_DOG" )
 public Dog dog;

接下来,我正在尝试使用Hibernate Session API来坚持使用新狗。

 @Transactional
 public void testAnimalJoinTable()
 {
      Dog dogFirst = new Dog();
      dogFirst.name = "FirstDog";

      Session session = sessionFactory.getCurrentSession();
      session.save( dogFirst );

      Dog dogSecond = new Dog();
      dogSecond.dog = dogFirst;
      dogSecond.name = "SecondDog";

      session.save( dogSecond );
 }

架构很好创建

  

Hibernate:创建表DOG(ANIMAL_ID bigint not null,ANIMAL_NAME varchar(255),主键(ANIMAL_ID))ENGINE = InnoDB
  Hibernate:创建表DOG_OTHER_DOG(dog_ANIMAL_ID bigint,ANIMAL_ID bigint非null,主键(ANIMAL_ID))ENGINE = InnoDB

但最后,Hibernate总是在save方法上失败并抛出。

  

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:'字段列表'中的未知列'dog_ANIMAL_ID'

实际上,Hibernate不使用连接表来保存狗。

  

Hibernate:从hibernate_sequences中选择sequence_next_hi_value,其中sequence_name ='ANIMAL'用于更新
  Hibernate:插入hibernate_sequences(sequence_name,sequence_next_hi_value)值('ANIMAL',?)
  Hibernate:更新hibernate_sequences设置sequence_next_hi_value =? sequence_next_hi_value =?和sequence_name ='动物'   Hibernate:插入DOG(ANIMAL_NAME,dog_ANIMAL_ID,ANIMAL_ID)值(?,?,?)

好吧,我的问题是(:

  • 为什么Hibernate不使用连接表? (如果我删除动物继承,一切正常)
  • 在我的情况下,我该如何解决问题?

提前致谢!


PS:我不能使用@MappedSuperclass来解决这个问题..

0 个答案:

没有答案