如何创建具有OnetoMany和ManytoOne关系的实体?

时间:2013-12-18 10:13:07

标签: mysql hibernate annotations

我创建了两个类,即Question.class和Option.class

@Entity
@Table(name="QUESTION")
public class Question {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="QID")
private String QID;

@Column(name="CCODE")
private String ccode;

@Column(name="CPCODE")
private String cpcode;

@Column(name="QUES_TYPE")
private String qtype;


@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name = "QUES_ID", referencedColumnName="QID")
@IndexColumn(name="idx")
private List<Options> Opt;  
}

和选项类是

@Entity
@Table(name="OPTIONS")
public class Options {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="OPTION_ID")
private String opid;

@Column(name="OPTION_TYPE")
private String optype;


@Column(name="OPTIONS")
private String optn;


@ManyToOne
@JoinColumn(name="QUES_ID")
private Question ques;
}

我写了一个简单的主类来插入数据

public void insertRow()
{
    Session s=getlSession(); 
      Transaction tx=s.beginTransaction();
 Question q=new Question("mah1", "cp1","text");
    Options op=new Options("text","b");
    op.setQues(q);
    s.save(q);
    s.save(op);

      tx.commit();
      s.close();
}

public static void main(String args[]){

    Test t=new Test();
    t.insertRow();


}

现在我在控制台中收到此错误..

Hibernate: insert into QUESTION (CCODE, CPCODE, QUES_TYPE) values (?, ?, ?)
Dec 18, 2013 3:29:28 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Dec 18, 2013 3:29:28 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'testing.QUESTION' doesn't exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not   execute statement at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.    java:82)

如果我取出2个实体之间的关系并执行该程序,它可以正常工作并在我的测试数据库中创建一个表。但是当我使用这种关系时,它不起作用。

1 个答案:

答案 0 :(得分:0)

  

错误:表'testing.QUESTION'不存在

- &GT;您必须创建QUESTION表。