我正在尝试使用Hibernate,我有一个类问题和一个类答案,它们之间存在一对一的关系,代码运行成功,但外键为空,我不知道为什么。
第一个
我的hibernate.cfg.xml
文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name = "hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name = "hibernate.connection.driver_class">com.mysql.jdbc.Driver </property>
<!-- Assume test is the database name -->
<property name = "hibernate.connection.url">jdbc:mysql://localhost:3306/aliens </property>
<property name = "hibernate.connection.username">root</property>
<property name = "hibernate.connection.password">root</property>
<property name = "hibernate.hbm2ddl.auto">create</property>
<property name = "show_sql">true</property>
<!-- List of XML mapping files -->
<mapping class= "io.com.learnHibernate.Question"/>
<mapping class= "io.com.learnHibernate.Answer"/>
</session-factory>
</hibernate-configuration>
我的主要职责
package io.com.learnHibernate;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.*;
import com.mysql.cj.xdevapi.SessionFactory;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
//configuration
Configuration conf=new Configuration();
conf.configure("Hibernate.cfg.xml");
org.hibernate.SessionFactory factory=conf.buildSessionFactory();
//creating answer
Answer a1=new Answer();
a1.setaId(180);
a1.setAnswer("my name is hafida");
//creating question
Question q1=new Question();
q1.setQuestionId(3);
q1.setQuestion("wht is your name?");
q1.setAnswer(a1);
//session
Session s=factory.openSession();
Transaction tx=s.beginTransaction();
//save
s.save(q1);
s.save(a1);
tx.commit();
// s.close();
// factory.close();
}
}
我希望插入外键的值,但它为空
1条答案
按热度按时间vof42yt11#
1.您需要在实体Map中指定级联类型:
1.当您使用双向@OneToOne时,您应该使两端同步:
1.然后您可以使用以下方式保存它: