本文介绍了使用一个连接表休眠一对多和Hibernate注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个连接表做两个表之间存在一个一对多的关系。

这就是为什么我要使用一个连接表:




最后,我想用Hibernate标注执行此。

我发现了一些例子来做到这一点使用XML映射但没有注释

我相信这会是怎样的表需要创建

  CREATE TABLE`PRODUCT`(
  `PRODUCT_ID` BIGINT PRIMARY KEY AUTO_INCREMENT
);CREATE TABLE`PARTS`(
  `PART_ID` BIGINT PRIMARY KEY AUTO_INCREMENT
); - USER_IMAGE_ID必须是唯一的,如果我们想产品与放大器之间存在一个一对多的关系;要素表
CREATE TABLE`USER_DETAILS_IMAGE`(
  `PRODUCT_ID` BIGINT,
  `PART_ID` BIGINT UNIQUE,
  约束`FK_PRODUCT_ID`外键(`PRODUCT_ID`)参考`PRODUCT`(`PRODUCT_ID`)
  约束`FK_PART_ID`外键(`PART_ID`)参考`PARTS`(`PART_ID`)
);


解决方案

不要找例子。读official文档:

  @Entity
公共类产品{    私人字符串的serialNumber;
    私人设置<部分>部分=新的HashSet<部分>();    @ID
    公共字符串getSerialNumber(){返回的serialNumber; }
    无效setSerialNumber(字符串SN){=的serialNumber SN; }    @OneToMany
    @JoinTable(
            NAME =PRODUCT_PARTS
            joinColumns = @JoinColumn(NAME =PRODUCT_ID),
            inverseJoinColumns = @JoinColumn(NAME =PART_ID)
    )
    公开组<部分>的getParts(){返回部分; }
    无效setParts(设置部分){this.parts =部分; }
}
@实体
公共类部分{
   ...
}

另外,请注意,这是对单向一对多关联的默认。所以,你甚至不必提供 @JoinTable 注释如果默认表和列名适合你。

I want do a one-to-many relationship between two tables using a join table.

This is why I want to use a join table:

Finally, I want to use Hibernate annotations to perform this.

I found some examples to do this using xml mapping but nothing with annotations.

I believe this would be how the tables need to be created

CREATE TABLE `PRODUCT` (
  `PRODUCT_ID`      BIGINT       PRIMARY KEY AUTO_INCREMENT
);

CREATE TABLE `PARTS` (
  `PART_ID`         BIGINT       PRIMARY KEY AUTO_INCREMENT
);

-- USER_IMAGE_ID must be unique if we want a one-to-many relationship between PRODUCTS & PARTS tables
CREATE TABLE `USER_DETAILS_IMAGE` (
  `PRODUCT_ID`      BIGINT,
  `PART_ID`         BIGINT UNIQUE,
  CONSTRAINT `FK_PRODUCT_ID`  FOREIGN KEY (`PRODUCT_ID`)   REFERENCES `PRODUCT`(`PRODUCT_ID`),
  CONSTRAINT `FK_PART_ID`     FOREIGN KEY (`PART_ID`)      REFERENCES `PARTS`(`PART_ID`)
);
解决方案

Don't look for examples. Read the official documentation:

@Entity
public class Product {

    private String serialNumber;
    private Set<Part> parts = new HashSet<Part>();

    @Id
    public String getSerialNumber() { return serialNumber; }
    void setSerialNumber(String sn) { serialNumber = sn; }

    @OneToMany
    @JoinTable(
            name="PRODUCT_PARTS",
            joinColumns = @JoinColumn( name="PRODUCT_ID"),
            inverseJoinColumns = @JoinColumn( name="PART_ID")
    )
    public Set<Part> getParts() { return parts; }
    void setParts(Set parts) { this.parts = parts; }
}


@Entity
public class Part {
   ...
}

Also, note that this is the default for unidirectional one-to-many associations. So you don't even have to provide the @JoinTable annotation if the default table and column names suit you.

这篇关于使用一个连接表休眠一对多和Hibernate注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 04:41