使用Hibernate保存对象

时间:2015-01-02 19:44:53

标签: java mysql hibernate jpa hibernate-mapping

我有3个表 - Rasskazi(主表),CatsRelations(表Rasskazi和表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只在名为rasskazi的表中保存记录:

Hibernate: 
    insert 
    into
        grabberRasskazov.rasskazi
        (rasskazName, rasskazText, rasskazDataDobav, rasskazRazmer) 
    values
        (?, ?, ?, ?)

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

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

catsRelationses.add(catsRelations);

}
r.setCatsRelationses(catsRelationses);

1 个答案:

答案 0 :(得分:2)

问题是您没有从Parent到Children实体级联:

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

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