Hibernate:这个类的id必须在调用save()之前手动赋值 [英] Hibernate: ids for this class must be manually assigned before calling save()

查看:1946
本文介绍了Hibernate:这个类的id必须在调用save()之前手动赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Hibernate和 oneToMany 映射中遇到了一些问题。



这是我的函数: p>

 位置位置=新位置(); 
location.setDateTime(new Date());
location.setLatitude(lat);
location.setLongitude(lon);

location = this.locationDao.save(location);

merchant = new Merchant();
merchant.setAddress(address);
merchant.setCity(city);
merchant.setCountry(country);
merchant.setLocation(location);
merchant.setName(name);
merchant.setOrganization(organization);
merchant.setPublicId(publicId);
merchant.setZipCode(zipCode);
merchant.setApplication(this.applicationDAO.findByPublicId(applicationPublicId));

merchant = this.merchantDao.save(merchant);

退货商家;

以下是我的两个实体:

Location

  import java.io.Serializable; 
import java.util.Date;
import java.util.List;
import javax.persistence。*;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;


@Entity
@Table(name =location)
@XmlRootElement
public class Location implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(可选= false)
@Column(name =id,nullable = false )
私人长ID;

@Basic(可选= false)
@NotNull
@Column(name =latitude,nullable = false)
私人双纬度;

@Basic(可选= false)
@NotNull
@Column(name =longitude,nullable = false)
私人双经度;

@Basic(可选= false)
@NotNull
@Column(name =date_time,nullable = false)
@Temporal(TemporalType.TIMESTAMP)
私人日期dateTime;

@OneToMany(cascade = CascadeType.ALL,mappedBy =location)
private List< Merchant> retailerList;

@OneToMany(cascade = CascadeType.ALL,mappedBy =location)
private List< MobileUser>用户列表;

public Location(){
}

public Location(Long id){
this.id = id;
}

公共位置(Long id,double latitude,double longitude,Date dateTime){
this.id = id;
this.latitude =纬度;
this.longitude = longitude;
this.dateTime = dateTime;
}

public Long getId(){
return id;
}
// getters and setters


@XmlTransient
public List< Merchant> getRetailerList(){
return retailerList;
}

public void setRetailerList(List< Merchant> retailerList){
this.retailerList = retailerList;
}

@XmlTransient
public List< MobileUser> getUserList(){
return userList;
}

public void setUserList(List< MobileUser> userList){
this.userList = userList;
}

@Override
public int hashCode(){
int hash = 0;
hash + =(id!= null?id.hashCode():0);
返回散列;
}

@Override
public boolean equals(Object object){
// TODO:Warning - 此方法在id字段为空没有设置
if(!(object instanceof Location)){
return false;
}
位置其他=(位置)对象; ((this.id == null&& other.id!= null)||(this.id!= null&&!this.id.equals(other.id)))
{
返回false;
}
返回true;
}

@Override
public String toString(){
returncom.fgsecure.geoloc.entities.Location [id =+ id +] ;
}

商家

  import java.io.Serializable; 
import javax.persistence。*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnore;


@JsonAutoDetect
@Entity
@Table(name =retailer)
@XmlRootElement

public class Merchant实现Serializable {

private static final long serialVersionUID = 1L;
@JsonIgnore
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(可选= false)
@Column(name =id,可为空= false)
私人长ID;
@Basic(可选= false)
@NotNull
@Size(min = 1,max = 50)
@Column(name =public_id,nullable = false,length = 50)
private String publicId;
@Basic(可选= false)
@NotNull
@Size(min = 1,max = 50)
@Column(name =name,nullable = false,length = 50)
私人字符串名称;
@Size(max = 50)
@Column(name =organization,length = 50)
private String organization;
@Size(max = 128)
@Column(name =address,length = 128)
私有字符串地址;
@Size(max = 10)
@Column(name =zip_code,length = 10)
private String zipCode;
@Size(max = 50)
@Column(name =city,length = 50)
private String city;
@Size(max = 50)
@Column(name =country,length = 50)
private String country;
@JoinColumn(name =location_id,referencedColumnName =id,nullable = false)
@ManyToOne(可选= false)
私人位置位置;
@JoinColumn(name =application_id,referencedColumnName =id,nullable = false)
@ManyToOne(可选= false)
私有应用程序应用程序;

$ b public Merchant(){
}

公共商户(Long id){
this.id = id;
}

公共商户(Long id,String publicId,String name){
this.id = id;
this.publicId = publicId;
this.name = name;


// getters and setters

$ b $ @Override
public int hashCode(){
int hash = 0 ;
hash + =(id!= null?id.hashCode():0);
返回散列;
}

@Override
public boolean equals(Object object){
// TODO:Warning - 此方法在id字段为空如果(!(对象instanceof商户)){
返回false,则不设置
;
}
商户其他=(商家)对象; ((this.id == null&& other.id!= null)||(this.id!= null&&!this.id.equals(other.id)))
{
返回false;
}
返回true;
}

@Override
public String toString(){
returncom.fgsecure.geoloc.entities.Retailer [id =+ id +] ;


$ / code $ / pre

我每次调用我的函数时都会得到:


  org.hibernate.id.IdentifierGenerationException:在调用save()之前,必须手动分配此类的ids:

为此行:

  location = this.locationDao.save(location); 

我不明白为什么。
因为在这种情况下,不需要手动分配位置ID,因为它是自动生成的。
我一定做了错误的事情,但3天后我看不到。



我使用PostGreSQL,id是自动生成的ID, :

  nextval('location_id_seq':: regclass)`

编辑解决:

确定感谢您的回答。



如果将来可以帮助其他人,只需要修改id的参数:

  @Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(可选= false)
@Column(name =id,unique = true,nullable = false)


解决方案

您的id属性未设置。这可能是由于DB字段未设置为自动增量的事实?你在用什么数据库? MySQL的?是你的领域设置为AUTO INCREMENT?


I am having some problems with Hibernate and the oneToMany mapping.

Here is my function:

        Location location = new Location();
        location.setDateTime(new Date());
        location.setLatitude(lat);
        location.setLongitude(lon);

        location = this.locationDao.save(location);

        merchant = new Merchant();
        merchant.setAddress(address);
        merchant.setCity(city);
        merchant.setCountry(country);
        merchant.setLocation(location);
        merchant.setName(name);
        merchant.setOrganization(organization);
        merchant.setPublicId(publicId);
        merchant.setZipCode(zipCode);
        merchant.setApplication(this.applicationDAO.findByPublicId(applicationPublicId));

        merchant = this.merchantDao.save(merchant);

        return merchant;

Here are my two entities:

Location

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;


@Entity
@Table(name = "location")
@XmlRootElement
public class Location implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id", nullable = false)
    private Long id;

    @Basic(optional = false)
    @NotNull
    @Column(name = "latitude", nullable = false)
    private double latitude;

    @Basic(optional = false)
    @NotNull
    @Column(name = "longitude", nullable = false)
    private double longitude;

    @Basic(optional = false)
    @NotNull
    @Column(name = "date_time", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateTime;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "location")
    private List<Merchant> retailerList;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "location")
    private List<MobileUser> userList;

    public Location() {
    }

    public Location(Long id) {
        this.id = id;
    }

    public Location(Long id, double latitude, double longitude, Date dateTime) {
        this.id = id;
        this.latitude = latitude;
        this.longitude = longitude;
        this.dateTime = dateTime;
    }

    public Long getId() {
        return id;
    }
    //getters and setters


    @XmlTransient
    public List<Merchant> getRetailerList() {
        return retailerList;
    }

    public void setRetailerList(List<Merchant> retailerList) {
        this.retailerList = retailerList;
    }

    @XmlTransient
    public List<MobileUser> getUserList() {
        return userList;
    }

    public void setUserList(List<MobileUser> userList) {
        this.userList = userList;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Location)) {
            return false;
        }
        Location other = (Location) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.fgsecure.geoloc.entities.Location[ id=" + id + " ]";
    }

Merchant

import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnore;


@JsonAutoDetect
@Entity
@Table(name = "retailer")
@XmlRootElement

public class Merchant implements Serializable {

    private static final long serialVersionUID = 1L;
    @JsonIgnore
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id", nullable = false)
    private Long id;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "public_id", nullable = false, length = 50)
    private String publicId;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "name", nullable = false, length = 50)
    private String name;
    @Size(max = 50)
    @Column(name = "organization", length = 50)
    private String organization;
    @Size(max = 128)
    @Column(name = "address", length = 128)
    private String address;
    @Size(max = 10)
    @Column(name = "zip_code", length = 10)
    private String zipCode;
    @Size(max = 50)
    @Column(name = "city", length = 50)
    private String city;
    @Size(max = 50)
    @Column(name = "country", length = 50)
    private String country;
    @JoinColumn(name = "location_id", referencedColumnName = "id", nullable = false)
    @ManyToOne(optional = false)
    private Location location;
    @JoinColumn(name = "application_id", referencedColumnName = "id", nullable = false)
    @ManyToOne(optional = false)
    private Application application;


    public Merchant() {
    }

    public Merchant(Long id) {
        this.id = id;
    }

    public Merchant(Long id, String publicId, String name) {
        this.id = id;
        this.publicId = publicId;
        this.name = name;
    }

   //getters and setters


    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Merchant)) {
            return false;
        }
        Merchant other = (Merchant) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.fgsecure.geoloc.entities.Retailer[ id=" + id + " ]";
    }
}

And each time I am calling my function I get:

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save():

for this line:

location = this.locationDao.save(location);

I don't understand why. Because in that case there is no need to manually assigne the id of location as it is auto generated. I must have done something wrong but after 3 days looking I don't find.

I am using PostGreSQL and the id is an autogenerated ID with this sequence:

nextval('location_id_seq'::regclass)`

EDIT SOLVE:

Ok Thanks for your answers.

If it can help other person in the future, just need to modify the param of the id by:

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id",unique=true, nullable = false)

解决方案

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?

这篇关于Hibernate:这个类的id必须在调用save()之前手动赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆