简体   繁体   English

休眠外键一对一单向

[英]Hibernate One-to-One unidirectional on foreign key

I have 2 table: 我有2张桌子:

   CREATE TABLE product(
  `id` INT NOT NULL AUTO_INCREMENT,
  // SOME OTHER DATA
  PRIMARY KEY (`id`));


 CREATE TABLE announce (
  `id` INT NOT NULL AUTO_INCREMENT,
  `productId` INT NOT NULL,
  // SOME OTHER DATA
  PRIMARY KEY (`id`),
  UNIQUE INDEX `productIdd_UNIQUE` (`productId` ASC),
  CONSTRAINT `FK_ANNOUNCE_PRODUCT`
    FOREIGN KEY (`productId`)
    REFERENCES `product` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE); 

I would like to realize One-to-One unidirectional on foreign key with hibernate 4 我想用休眠4在外键上实现一对一单向

here my configuration hbm.xml : 这是我的配置hbm.xml:

<hibernate-mapping>
    <class name="mypackage.Announce" table="announce">
        <id name="id" type="int">
            <column name="id" />
            <generator class="native" />
        </id>
        <one-to-one name="product" foreign-key="productId" cascade="all-delete-orphan" lazy="false" />
      ...
    </class>
</hibernate-mapping>



<hibernate-mapping>
    <class name="mypackage.Product" table="product">
        <id name="id" type="int">
            <column name="id" />
            <generator class="native" />
        </id>
        ...
    </class>
</hibernate-mapping>

I'm able to get the data in base, but when i tried to create an announce with an existing product my code throw an SQLException 我可以从数据库中获取数据,但是当我尝试使用现有产品创建公告时,我的代码抛出SQLException

22:56:17.565 DEBUG ohejdbc.spi.SqlExceptionHelper - could not execute statement [n/a] java.sql.SQLException: Field 'productId' doesn't have a default value 22:56:17.565调试ohejdbc.spi.SqlExceptionHelper-无法执行语句[n / a] java.sql.SQLException:字段“ productId”没有默认值

The save generate the id of my foreign key, but i don't understand why. 保存生成我的外键的ID,但我不明白为什么。

the java code (my dao make base instruction like sessionFactory.save etc...): Java代码(我的dao使基本指令如sessionFactory.save等...):

Announce announce = new Announce();
...
Product product = this.productDao.getProduct(productId);
announce.setProduct(product);

this.announceDao.save(announce);

Someone have an idea how to solve my problem ? 有人知道如何解决我的问题吗?

Your current configuration tells hibernate to use the primary key as association between both tables, where you want to use a separate column (at least that is what you ddl allows). 您当前的配置告诉hibernate使用主键作为两个表之间的关联,您要在其中使用单独的列(至少这是ddl允许的)。

A one-to-one mapping in xml should be defined with a <many-to-one unique="true" column=".."/> . xml中的一对一映射应使用<many-to-one unique="true" column=".."/> This is very confusing, I agree. 我同意,这非常令人困惑。

<hibernate-mapping>
  <class name="mypackage.Announce" table="announce">
  ...
    <many-to-one name="product" columm="productId" cascade="all-delete-orphan" lazy="false" unique="true"/>
 ... 
  </class>
</hibernate-mapping>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM