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

时间:2016-04-27 03:33:33

标签: java hibernate jpa spring-boot spring-data

    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。当我尝试在没有登录的情况下保存客户时,它工作正常,但问题是我无法在数据库中保存登录对象。

我收到错误说

  

“字段列表”中的未知列'id_customer'   生成了jpa实体。

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

enter image description here

2 个答案:

答案 0 :(得分:1)

示例中的idCustomer太多了。

尝试以下代码。 我更改了注释成员@OneToMany和@ManyToOne, 按照此处建立的提示JPA JoinColumn vs mappedBy

我也在Login类中包含了idLogin。我不知道这是否是您代码中的拼写错误。

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;

}

答案 1 :(得分:0)