为什么我得到org.hibernate.id.IdentifierGenerationException?

当我运行我的主类 (Runner)程序时,我得到以下exception:

 org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property: country 

我不知道原因,为什么我得到这个例外。

映射xml:

            country       

POJO课程:

国家

 public class Country { private int countryID; private String countryName; private PM pm; public PM getPm() { return pm; } public void setPm(PM pm) { this.pm = pm; } public int getCountryID() { return countryID; } public void setCountryID(int countryID) { this.countryID = countryID; } public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } } 

下午

 public class PM { private int countryID; private String pmName; private Country country; public int getCountryID() { return countryID; } public void setCountryID(int countryID) { this.countryID = countryID; } public String getPmName() { return pmName; } public void setPmName(String pmName) { this.pmName = pmName; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } } 

这是尝试提交事务的类:

 public class Runner { public static void main(String args[]) {System.out.println("dfdf"); Configuration config = new Configuration().configure(); SessionFactory sessFact = config.buildSessionFactory(); Session session = sessFact.openSession(); Transaction trans = session.beginTransaction(); Country c = new Country(); PM pm = new PM(); pm.setPmName("Manmohan Singh"); c.setCountryName("India"); c.setPm(pm); session.save(c); trans.commit(); } } 

创建表的SQL:

 CREATE TABLE country(c_id INTEGER,c_name TEXT,PRIMARY KEY(c_id)); CREATE TABLE pm(c_id INTEGER,pm_name TEXT); 

问题是country变量。 在尝试执行某些事务之前,您应该初始化所有的attirbutes。

编辑:在您的Hibernate文件中,您希望从country属性的ID生成PM ID。 但是,此属性从未初始化。

     country      

所以,添加pm.setCountry(c); 你的代码。