开发者

EclipseLink deleting referenced entity

开发者 https://www.devze.com 2023-03-08 15:54 出处:网络
I\'m using EclipseLink as my persistance unit. I\'m having a problem on deleting an entity. Following example: a device has a type. There are many devices which could have the same type.

I'm using EclipseLink as my persistance unit. I'm having a problem on deleting an entity. Following example: a device has a type. There are many devices which could have the same type. I inserted a view types and devices (which refer to a type). If I'm now delete a type (which a device refers to) the entity is deleted from the database. This shouldn't happen since a device refers to that type. What I'm doing wrong?

Thanks in advance!

I'm deleting like the following:

EntityManager em = factory.createEntityManager();
em.getTransaction().begin();

Query q = em.createQuery("SELECT d FROM DeviceType d WHERE d.name = :name");
q.setParameter("name", "Name");
Type type = (Type)q.getSingleResult();

em.remove(type);
em.getTransaction().commit();
em.close();

My en开发者_C百科tities:

@Entity
public class Device {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToOne
    @JoinColumn(name="TYPE_ID", nullable = false)
    private Type type;
}
@Entity
public class Type {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true, nullable = false)
    private String name;    
}


I'm not sure I'm clear on the problem though - are you expecting an exception when you call remove(type)? If so, check that you have a database constraint set on the Device->Type relationship which will throw an exception on delete. How are the tables created?

If the problem is you are getting an exception - its because you shouldn't delete an entity without cleaning up references to it first. Should query for the Device and fix any references to the Type before you delete it Ie:

Query q = em.createQuery("SELECT device FROM Type device WHERE device.type.name :name"); 
q.setParameter("name", "Name"); 
List devices = q.getResultList();  

Each returned device in the collection should reference the same type instance, so you can remove it afterward. You could also change the mapping to be ManyToOne and then set a OneToMany in Type back to device if you want to be able to access them from a type instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号