简体   繁体   English

@ManyToOne @OneToMany 映射,外键为 null

[英]@ManyToOne @OneToMany Mapping , foreign key is null

@Entity
@Data
@NoArgsConstructor
public class Offer {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    private User user;
}

@Data
@EqualsAndHashCode
@Entity
@NoArgsConstructor
public class User  {
    @OneToMany(mappedBy = "user",cascade = CascadeType.ALL,fetch=FetchType.LAZY)
    private Set<Offer> offers = new HashSet<Offer>();
}

Please help if the mapping is correct in table User and Offer.user_id column have null values....:(如果表 User 和 Offer.user_id 列中的映射正确,请提供帮助,该列具有 null 值....:(

I'm not sure if these are only parts of the entities but in order for the entity to have an id, you need to provide it with one and annotate the relevant field as @Id.我不确定这些是否只是实体的一部分,但为了让实体拥有一个 id,您需要为其提供一个并将相关字段注释为 @Id。 I also use @GeneratedValue(strategy = GenerationType.IDENTITY) so each table will get it's own id (generated by Hibernate, you don't provide the id when you save a new entity and not a global id, otherwise let's say you add an Offer, you get id with value x, then add new User you get id with value x+1 and so on...我也使用@GeneratedValue(strategy = GenerationType.IDENTITY) 所以每个表都会得到它自己的id(由Hibernate生成,当你保存一个新实体而不是全局id时你不提供id,否则假设你添加一个提供,您获得值为 x 的 id,然后添加新用户,您获得值为 x+1 的 id,依此类推...

@Entity
@Data
@NoArgsConstructor
public class Offer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    private User user;

}



@Data
@EqualsAndHashCode
@Entity
@NoArgsConstructor
public class User  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
   private long id;
     @OneToMany(mappedBy = "user",cascade = CascadeType.ALL,fetch=FetchType.LAZY)
    private Set<Offer> offers = new HashSet<Offer>();
}`

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

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