我有一个包含五个数据的节点数据库:
和同一个表中的两个外键
这是我的豆子
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column(name="id")
@NotNull
private int id;
@Column (name = "question")
private String question;
@Column ( name = "result")
private String result;
@OneToOne(fetch= FetchType.LAZY)
@JoinColumn(name="left_id", referencedColumnName="id", insertable=true, updatable=true)
private Nodes left;
@OneToOne(fetch= FetchType.LAZY)
@JoinColumn(name="right_id", referencedColumnName="id", table="node", insertable=true, updatable=true)
private Nodes right;
这是我的道歉
public void insert_question(String question, int left) throws HibernateException
{
try
{
Session session = getSession();
Transaction tx = session.beginTransaction();
Nodes node = new Nodes();
Nodes leftNode = new Nodes();
//insert question
node.setQuestion(question);
// insert left_id with fk
leftNode.setId_node(left);
node.setLeftNodes(leftNode);
session.saveOrUpdate(node);
tx.commit();
session.close();
}
catch (HibernateException e)
{
e.printStackTrace();
}
}
我对结果有相同的插入方法但没有外键。
我的新问题和新结果是插入我的数据库,但不是我的left_id。
在Eclipse中,hibernate告诉我
Infos: Hibernate: select nodes_.id, nodes_.question as question0_, nodes_.result as result0_ from node nodes_ where nodes_.id=?
Infos: Hibernate: insert into node (question, result, id) values (?, ?, ?)
Infos: Hibernate: insert into node (question, result, id) values (?, ?, ?)
当hibernate插入新数据时,为什么没有left / right_id?
感谢
编辑:
我改变了我的习惯。在此之前
<hibernate-mapping>
<class name="com.beans.Nodes" table="node">
<id name="id" type="int" access="field">
<column name="id" />
<generator class="assigned" />
</id>
<property name="question" type="java.lang.String">
<column name="question" />
</property>
<property name="result" type="java.lang.String">
<column name="result" />
</property>
<one-to-one name="left" class="com.beans.Nodes" access="field"></one-to-one>
<one-to-one name="right" class="com.beans.Nodes" access="field"></one-to-one>
</class>
</hibernate-mapping>
现在就像那样
<hibernate-mapping>
<class name="com.beans.Nodes" table="node">
<id name="id" type="int" access="field">
<column name="id" />
<generator class="assigned" />
</id>
<property name="question" type="java.lang.String">
<column name="question" not-null="false"/>
</property>
<property name="result" type="java.lang.String">
<column name="result" not-null="false"/>
</property>
<many-to-one name="Left"
column="left_id"
unique="true"
not-null="false"
/>
<many-to-one name="Right"
column="right_id"
unique="true"
not-null="false"
/>
</class>
</hibernate-mapping>
它的确有效!