休眠:无法删除|删除已分离的实例

时间:2018-01-14 23:21:09

标签: java hibernate

我正在创建一个简单的api,我可以在其中存储图像并对它们执行crud功能。为了与数据库通信,我使用了Hibernate。在获取数据的过程中,我无法添加或删除数据。这将导致add;

的这个例外
  

org.hibernate.exception.GenericJDBCException:无法执行语句

和删除的这个例外;

  

删除分离的实例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并未自动发布。现在我换成了ai,它运行正常。删除仍然无效:&#39;(

1 个答案:

答案 0 :(得分:1)

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

  1. 您滥用实体经理。每个实体应属于一个实体管理器。如果使用一个实体管理器加载实体,然后使用另一个实体管理器保存它,则可能会出现错误,例如删除分离的实例com.mycompany.server.model.Image#0
  2. 仅当没有例外时,才会为实体管理员调用 close 。如果在调用 close 之前异常会上升,您将获得资源泄漏。尝试使用try-with-resources。
  3. 您根据生成的标识符为实体实现了equals和heshCode。这是不好的做法。如果您没有Image的其他相等条件 - 请勿覆盖 equals hashCode
  4. 也许这个笔记会对你有帮助。