有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate:无法删除|删除分离的实例

我正在制作一个简单的api,在这里我可以存储图像并对其执行crud功能。为了与数据库通信,我使用Hibernate。虽然获取数据进展顺利,但我无法添加或删除数据。这将导致add出现此异常

org.hibernate.exception.GenericJDBCException: could not execute statement

此例外情况为删除

Removing a detached instance com.mycompany.server.model.Image#0

我不知道它为什么做不到这项工作。它以前是有效的,我没有做任何改变。希望你能找到问题所在。如果这些信息还不够,只需评论你想看到的内容即可

这是您的模型:

@Entity
@Table(name = "image")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@NamedQueries({
@NamedQuery(name = "Image.findAll", query = "SELECT i FROM Image i")
, @NamedQuery(name = "Image.findByImageId", query = "SELECT i FROM Image i WHERE i.imageId = :imageId")
, @NamedQuery(name = "Image.findByContenttype", query = "SELECT i FROM Image i WHERE i.contenttype = :contenttype")
, @NamedQuery(name = "Image.findByName", query = "SELECT i FROM Image i WHERE i.name = :name")
, @NamedQuery(name = "Image.findByDescription", query = "SELECT i FROM Image i WHERE i.description = :description")})
public class Image implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @XmlElement(nillable=true)
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Basic(optional = false)
    @NotNull
    @Column(name = "image_id")
    private Integer imageId;

    @Basic(optional = false)
    @NotNull
    @Lob
    @Size(min = 1, max = 16777215)
    @Column(name = "content")
    private String content;

    @Basic(optional = false)
    @Size(min = 1, max = 45)
    @Column(name = "contenttype")
    private String contenttype;

    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 45)
    @Column(name = "name")
    private String name;

    @Size(max = 45)
    @Column(name = "description")
    private String description;

    public Image() {
    }

    public Image(Integer imageId) {
        this.imageId = imageId;
    }

    public Image(Integer imageId, String content, String contenttype, String name) {
        this.imageId = imageId;
        this.content = content;
        this.contenttype = contenttype;
        this.name = name;
    }

    public Integer getImageId() {
        return imageId;
    }

    public void setImageId(Integer imageId) {
        this.imageId = imageId;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getContenttype() {
        return contenttype;
    }

    public void setContenttype(String contenttype) {
        this.contenttype = contenttype;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (imageId != null ? imageId.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 Image)) {
            return false;
        }
        Image other = (Image) object;
        if ((this.imageId == null && other.imageId != null) || (this.imageId != null && !this.imageId.equals(other.imageId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.mycompany.server.model.Image[ imageId=" + imageId + " ]";
    }

}

以及服务的实施:

public class ImageRepositoryServiceImpl implements ImageRepositoryService    {

    private EntityManagerFactory entityManagerFactory;

    private static ImageRepositoryServiceImpl instance;

    private ImageRepositoryServiceImpl() {
        entityManagerFactory = Persistence.createEntityManagerFactory("com.mycompany_server_war_1.0-SNAPSHOTPU");
    }

    static {
        instance = new ImageRepositoryServiceImpl();
    }

    private EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }

    public static ImageRepositoryService getInstance() {
        return instance;
    }

    @Override
    public List<Image> getAllImages() {
        EntityManager em = entityManagerFactory.createEntityManager();
       List<Image> images = em.createNamedQuery("Image.findAll", Image.class).getResultList();
        em.close();
        return images;
    }

    @Override
    public Image getImageFromId(int imageId) {
        EntityManager em = entityManagerFactory.createEntityManager();
        Image image = em.find(Image.class, imageId);
        em.close();        
        return image;
    }

    @Override
    public boolean addImage(Image image) {
        try{
            EntityManager em = entityManagerFactory.createEntityManager();
            em.getTransaction().begin();
            em.persist(image);
            em.getTransaction().commit();
            em.close();        
            return true;
        }catch(Exception e){
            return false;
    }              
}

    @Override
    public boolean editImage(Image image) {
        throw new UnsupportedOperationException("Not supported yet. edit"); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean DeleteImage(Image image) {
        try{
            EntityManager em = entityManagerFactory.createEntityManager();
            em.remove(image);
            return true;
        }catch(Exception e){
            return false;
        }
    }

}

编辑:

我解决了这个问题。显然image_id不是自动激励的。现在我改为人工智能,它工作得很好。但删除仍不起作用:'(


共 (1) 个答案

  1. # 1 楼答案

    我在此代码中看到了哪些问题:

    1. 您滥用了实体管理器。每个实体应属于一个实体经理。如果使用一个实体管理器加载实体,然后使用另一个实体管理器保存,则可能会出现错误,例如删除分离的实例com。我的公司。服务器模型图像#0
    2. 只有在没有异常的情况下,才能为实体管理器调用close。如果异常在调用close之前出现,您将得到资源泄漏。尝试使用Try-with资源
    3. 您根据生成的标识符为实体实现了equals和heshCode。这是坏习惯。如果图像没有其他相等条件,请不要覆盖equalshashCode

    也许这些笔记会对你有所帮助