【问题标题】:hibernate & jpa : table with composite primary key : auto increment problemhibernate & jpa:具有复合主键的表:自动增量问题
【发布时间】:2018-12-15 17:20:59
【问题描述】:

我有那些实体:

@Entity
public class Carburant implements Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_carburant")
    private long id;
    private String nom;
    private String description;

    @JsonIgnore
    @OneToMany(mappedBy="carburant")
    private Set<HistCarb> stations ;

    public Carburant() {
        super();
    }
}

2

@Entity
@Table(name="Station")
public class Station implements Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_station")
    private long id ;
    private String nom;
    private String ville;
    private String adresse;

    @Transient
    private boolean nul = false;

    @JsonIgnore
    @OneToMany(mappedBy="station")
    private Set<HistCarb> historiques ;

    public Station() {
        super();
    }
}

3

@Entity

public class HistCarb implements Serializable{

    @Id
    @Column(name="id",updatable=false,nullable=false)
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;

    private Date date;
    private Integer prix;

    @Id
    @ManyToOne
    @JoinColumn(name="id_station")

    private Station station ;

    @Id
    @ManyToOne
    @JoinColumn(name="id_carburant")
    private Carburant carburant ;


    public HistCarb() {
        super();

    }
}

类图: enter image description here

她的问题是:hibernate 给我这个表 HistCarb 的 sql 代码:

create table HistCarb (
       id bigint not null,
        date datetime,
        prix integer,
        id_station bigint not null auto_increment,
        id_carburant bigint not null,
        primary key (id_station, id, id_carburant)
    ) engine=InnoDB

使用 id_station auto_increment,但我希望 hibernate 只生成列 id 作为 auto_increment 字段,正如我在实体 3 中提到的那样 我希望有人可以帮助我解决这个问题。 我没有为实体 3 使用嵌入式 ID 我认为我们可以在没有嵌入式 ID 的情况下做到这一点,因为我发现它很难实现,当我尝试在这种情况下使用嵌入式 ID 时会出现一些错误。

【问题讨论】:

  • 当自动递增字段为@Id 时,为什么要将FK 字段标记为@Id?毫无意义

标签: java mysql hibernate jpa


【解决方案1】:

HistCarb 中,@Id 在 3 个字段上,这就是为什么你会得到一个复合键。从stationcarburant 中删除@Id,如下所示:

@Entity
public class HistCarb implements Serializable{

    @Id
    @Column(name="id",updatable=false,nullable=false)
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;

    private Date date;
    private Integer prix;

    @ManyToOne
    @JoinColumn(name="id_station")

    private Station station ;

    @ManyToOne
    @JoinColumn(name="id_carburant")
    private Carburant carburant ;


    public HistCarb() {
        super();

    }
}

【讨论】:

    猜你喜欢
    • 2011-06-08
    • 2018-02-02
    • 1970-01-01
    • 2020-02-19
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    相关资源
    最近更新 更多