发生PersistenceException:org.hibernate.exception.ConstraintViolationException:无法插入:[models.User]

时间:2012-05-20 05:32:26

标签: java hibernate playframework

我有这个例外!! 这是我的模型类

@Entity
public class User extends Model {

    @OneToMany(mappedBy="email", cascade=CascadeType.ALL)
    public List<Photo> photo;

    @Email
    @Required
    @Unique
    public String email;

    @Required
    public String passwordHash;

    @Required
    public String education;

    @Required
    public String fname;

    @Required
    public String lname;

    @Required
    public Date dob;

    @Required
    public String gender;

    @Required
    public String country;

    @Required
    public Long phone;

    @Required
    public String status;

    @Required
    public String jobtitle;

    @Required
    public String company;

    @Required
    public String industry;

    @Required
    public Date addDate;

    public String needConfirmation;

public User(String email, String password, String fname,
                String lname, Date dob, String gender, String country,
                Long phone, String status, String education, String jobtitle, String company, String industry) {
        //all initialization here
    }
}
你可以告诉我哪里出错了吗? playframework×2289


this is my photo class, and please tell me how can I allow JPA to generate my database


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package models;

import controllers.Users;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import play.db.jpa.Model;

/**
 *
 * @author nPandey
 */
@Entity
public class Photo extends Model{

    public String photoname;

    @ManyToOne
    public User email;

    public String owner;

    public Photo(){

    }

    public Photo(User email, String photo){
        this.photoname=photo;
        this.email=email;
        this.owner=email.email;
    }

}

4 个答案:

答案 0 :(得分:0)

检查您的实体在保留/更新时是否缺少任何必填字段。还要检查DB中User-table上设置的约束(唯一键,外键,非空值......)。

答案 1 :(得分:0)

您的mappedBy值毫无意义。它用于双向关联的被动端。在这些情况下,它指向关系另一侧的另一个类的属性。您将其指向User类的其中一个属性。也许您的Photo类具有email属性,但属于User类型(我猜不是)。因此,如果这是双向关联,请将mappedBy值设置为Photo上具有相应@ManyToOne“返回”的User的属性。如果它是单向关联,则删除mappedBy并使用@JoinColumn来使用单向一对多的外键映射策略

答案 2 :(得分:0)

我遇到了同样的问题,并通过将关系相关的符号从OneToMany更改为ManyToMany来解决。在我的情况下,Job和Person Table之间存在ManyToMany关系,我试图在循环中将同一个jobList添加到多个person对象。

问题在于Job Entity的Person Entity类中使用的注释:

@ManyToMany // Changed from OneToMany to ManyToMany
private List<Job> jobList = new ArrayList<Job>();

答案 3 :(得分:0)

尝试编辑以下代码 - 在用户模型中

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    public List<Photo> photos;

在照片模型中

    @ManyToOne
    @NotFound(action = NotFoundAction.IGNORE)
    @JoinColumn(name = "email", nullable = false, insertable = false, updatable = false)
    public User user;

选中此项以供参考 - http://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Example_of_a_OneToMany_relationship_and_inverse_ManyToOne_annotations