用hibernate更新fk

时间:2016-10-05 09:15:31

标签: java mysql hibernate foreign-keys

我的图片表与User表有两个OneToOne关系:

ERD

图片实体:

@Entity
@Table(name = "pictures")
public class Picture implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    public int getId() {
        return id;
    }

    @OneToOne
    @JoinColumn(name = "customer_id", nullable = true)
    private User customer;

    public User getCustomer() {
        return customer;
    }

    public void setCustomer(User customer) {
        this.customer = customer;
    }

    @OneToOne
    @JoinColumn(name = "photographer_id", nullable = false)
    private User photographer;

    public User getPhotographer() {
        return photographer;
    }

    public void setPhotographer(User photographer) {
        this.photographer = photographer;
    }

    private String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    private String url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    private BigDecimal price;

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }


    public Picture(String title,
                   String url,
                   BigDecimal price)
    {
        this.title = title;
        this.url = url;
        this.price = price;
    }

    public Picture() {
        // Empty constructor
    }
}

PictureDaoImpl:

@Override
public void insert(Picture object) {
    sessionFactory.getCurrentSession().save(object);
}

如何更新两个外键customer_idphotographer_id

在实体中,两个外键是与User

的OneToOne关系

我得到的错误是Column 'photographer_id' cannot be null

1 个答案:

答案 0 :(得分:0)

您的数据库设计极其错误。

在DB实体之间,您不能在表\实体之间建立两个关系 只能和唯一的关系。

根据您的设计,您需要@OneToManyPicture之间User关系的关系,对于您拥有许多用户的每一张/每张图片,即使事实上您最终也会只有两个用户,因为两个用户仍然不是一个/一个,所以它被认为是多个用户。

我建议先重新设计数据库。