java Hibernate:必须在调用保存()之前手动分配此类的ID

hm2xizp9  于 2023-02-02  发布在  Java
关注(0)|答案(3)|浏览(107)

我在Hibernate和oneToManyMap方面遇到了一些问题。
下面是我的函数:

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;

下面是我的两个实体:

    • 地点**
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 + " ]";
    }
    • 商人**
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 + " ]";
    }
}

每次调用函数时,我得到:

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

对于此行:

location = this.locationDao.save(location);

我不明白为什么。因为在这种情况下,没有必要手动分配的ID的位置,因为它是自动生成的。我一定是做错了什么,但经过3天的寻找,我没有找到。
我使用的是PostGreSQL,ID是自动生成的ID,序列如下:

nextval('location_id_seq'::regclass)`
    • 编辑求解:**

好的谢谢你的回答.
如果将来可以帮助其他人,只需修改id的参数:

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

yzuktlbb1#

你的id属性没有被设置。2这可能是由于数据库字段没有被设置为自动递增?3你使用的是什么数据库?4 MySQL?5你的字段被设置为自动递增?

r7knjye2

r7knjye22#

∮ ∮ ∮ ∮
确保属性是主键,并且是数据库中的Auto Incrementable,然后使用IDENTITY将其Map到带有@GeneratedValue注解的数据类中。

@Entity
@Table(name = "client")
data class Client(
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id") 
    private val id: Int? = null
)

GL语言
Source

x6492ojm

x6492ojm3#

1.标识在数据库架构中创建的序列的名称

SELECT sequence_schema, sequence_name FROM information_schema.sequences ORDER BY sequence_name;

2.确保序列名称与实体中的关联名称匹配

公共类Calmicprsusc {私有静态最终长序列版本UID = 1 L;

@GenericGenerator(
        name = "calmicprsuscGen",
        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @org.hibernate.annotations.Parameter(name = "sequence_name", value = "calmicprsusc_idcalmicprsusc_seq"),
                @org.hibernate.annotations.Parameter(name = "initial_value", value = "1"),
                @org.hibernate.annotations.Parameter(name = "increment_size", value = "1")}
)

@Id
@GeneratedValue(strategy= GenerationType.SEQUENCE, generator="calmicprsuscGen")
@Column(name = "idcalmicprsusc")
private Integer idcalmicprsusc;  

@Column(name = "idsample")
private Integer idsample;

}

相关问题