gpt4 book ai didi

java - 如何使用spring DAO保存外键实体

转载 作者:行者123 更新时间:2023-12-01 10:00:02 24 4
gpt4 key购买 nike

    public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idCustomer")
private Integer idCustomer;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "idCustomer")
private Collection<Login> loginCollection;

}

public class Login implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idLogin")

@JoinColumn(name = "idCustomer", referencedColumnName = "idCustomer")
@ManyToOne(optional = false)
private Customer idCustomer;

}

//trying to save the customer and login in the database

ArrayList<Login> logins = new ArrayList<Login>();
Login log = new Login();
log.setIdCustomer(cust);
logins.add(log);
cust.setLoginCollection(logins);
cust = custRepo.save(cust); //failed

//Login log = new Login();
//log.setUName(user);
//log.setPassword(pass);
//log.setIdCustomer(cust);
//cust = custRepo.save(cust);
//logRepository.save(log); //failed too.

我在我的项目中使用 spring 数据。我有 2 个模型类 CustomerLogin。我的登录类在数据库中有一个外键 idCustomer 。当我尝试在没有登录的情况下保存客户时,它工作正常,但问题是我无法在数据库中保存登录对象。

我收到一条错误消息

Unknown column 'id_customer' in 'field list' the jpa entities are generated.

这是一个图像实际数据库。

enter image description here

最佳答案

您的示例中的 idCustomer 过多。

尝试下面的代码。我对带注释的成员@OneToMany 和@ManyToOne 做了一些更改,遵循此处建立的提示 JPA JoinColumn vs mappedBy

此外,我已将 idLogin 包含在 Login 类中。我不知道这是否是您代码中的拼写错误。

public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idCustomer")
private Integer idCustomer;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
private Collection<Login> loginCollection;

}

public class Login implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idLogin")
private Integer idLogin;

@ManyToOne
@JoinColumn(name="idCustomer", insertable=false, updatable=false)
private Customer customer;

}

关于java - 如何使用spring DAO保存外键实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36879770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com