使用 Hibernate 保存对象

Saving object with Hibernate

我有 3 个 tables - Rasskazi(主要 table)、CatsRelations(table Rasskazi 和 table CatsNames 之间的关系)和 CatsNames。

CREATE TABLE `rasskazi` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `rasskazName` varchar(777) DEFAULT NULL,
  `rasskazText` text,
  `rasskazDataDobav` datetime DEFAULT NULL,
  `rasskazRazmer` float DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

CREATE TABLE `catsRelations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `rasskazId` int(11) DEFAULT NULL,
  `catId` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `rasskazIdFK_idx` (`rasskazId`),
  KEY `catIdFK_idx` (`catId`),
  CONSTRAINT `z1` FOREIGN KEY (`rasskazId`) REFERENCES `rasskazi` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `z2` FOREIGN KEY (`catId`) REFERENCES `catsNames` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `catsNames` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `catName` varchar(777) DEFAULT NULL,
  `oldId` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `oldId_UNIQUE` (`oldId`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;

Hibernate 对象是:

Rasskazi.hbm.xml [http://pastebin.com/CF4D47M1][1]
Rasskazi.java [http://pastebin.com/29phnEEd][2]
CatsRelations.hbm.xml [http://pastebin.com/MqnXuAQ9][3]
CatsRelations.java [http://pastebin.com/BDqTKqeD][4]
CatsNames.hbm.xml [http://pastebin.com/9YtVkCjD][5]
CatsNames.java [http://pastebin.com/uwpWcLha][6]

所有文件都打包成 zip 文件,可以下载 here

我尝试通过代码保存对象

Rasskazi r = new Rasskazi();
    r.setRasskazName(storyName);
    Set<CatsRelations> catsRelationses = new HashSet<>();
    Elements katsInfo = doc.select("a[href*=ras.shtml?kat]");
    for (Element kat : katsInfo) {
        String katId = kat.attr("href");
        CatsNames cat = mainBean.getCat(katId); // Here I got CatsNames from my bean, from table named CatsNames

        CatsRelations catsRelations = new CatsRelations();
        catsRelations.setCatsNames(cat);
        catsRelations.setRasskazi(r);

        catsRelationses.add(catsRelations);

    }
    r.setCatsRelationses(catsRelationses);
    r.setRasskazText(textStr);
    Session session = sessionFactory.getCurrentSession();
    session.save(r);

但 Hibernate 仅在 table 命名的 rasskazi:

中保存记录
Hibernate: 
    insert 
    into
        grabberRasskazov.rasskazi
        (rasskazName, rasskazText, rasskazDataDobav, rasskazRazmer) 
    values
        (?, ?, ?, ?)

并且它不会将任何数据保存到名为 table 的 CatsNames。 为什么它不将数据保存到 table CatsNames,为什么它忽略代码

CatsRelations catsRelations = new CatsRelations();
catsRelations.setCatsNames(cat);
catsRelations.setRasskazi(r);

catsRelationses.add(catsRelations);

}
r.setCatsRelationses(catsRelationses);

?

问题是您没有从父实体级联到子实体:

<set name="children" inverse="true" cascade="all">
    <key column="parent_id"/>
    <one-to-many class="Child"/>
</set>

确保将级联添加到所有一对多关联。