本文介绍了JPA从数据库创建,编辑和删除实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何使用实体尽可能简单地管理创建,编辑和删除操作?

How should I manage the create, edit and delete operations with entites as simple as possible?

例如:

用户:

public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;

    ...

    // Item can't exist without user
    @OneToMany(cascade=CascadeType.ALL,mappedBy = "user",orphanRemoval=true)
    private Set<Item> items = new HashSet<Item>();

    public Set<Item> getItems() { return items; }

    public void addItem(Item item) {
        items.add(item);
    }

    public void removeItem(Item item) {
        if(!items.contains(item)) return;
        items.remove(item);
    }

    // Group can exist without a user
    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH},mappedBy="users")
    private Set<Group> groups = new HashSet<Group>();

    public Set<Group> getGroups() { return groups; }

    public void setGroups(Set<Group> groups) { this.groups = groups; }

    public void addGroup(Group group) {
        groups.add(group);
    }

    publi void removeGroup(Group group) {
        if(!groups.contains(group)) return;
        groups.remove(group);
    }

    ...
}

组:

@Entity
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;

    ...

    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name = "GroupToUser", joinColumns =
    @JoinColumn(name = "GroupId", referencedColumnName="Id"), inverseJoinColumns =
    @JoinColumn(name = "UserId", referencedColumnName="Id"))
    private Set<User> users = new HashSet<User>();

    public Set<User> getUsers() { return users; }

    public void setUsers(Set<User> users) { this.users = users; }

    public void addUser(User user) {
        user.addGroup(this);
    }

    publi void removeUser(User user) {
        if(!users.contains(user)) return;
        users.remove(user);
    }

    ...
}

项目:

@Entity
public class Item {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;

    ...

    @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="UserId")
    private User user;

    public Set<User> getUser() { return user; }

    public void setUser(User user) {
        this.user = user;
    }

    publi void removeUser() {
        this.user = null;
    }

    ...
}

我使用jpa注释了吗?

Am I using the jpa annotations right?

我应该在这里写些什么?

What should I write here?

EntityManager em = getEntityManager();
em.getTransaction().begin();
???
em.getTransaction().commit();

我是否只需要调用em.remove/persist/merge方法进行删除/创建/编辑操作?

Do I have to just call the em.remove/persist/merge methods for delete/create/edit operations?

这些操作何时应使用javax.persistence.EntityManager.getReference方法?

And when should I use the javax.persistence.EntityManager.getReference method in these operations?

推荐答案

Find()从持久性上下文的缓存中提供实体,如果该实体不在缓存中,则将从数据库中加载该实体.

Find() delivers the entity from the cache of the persistence context or if he is not there, it will be loaded from the database.

GetReference()不会立即加载实体.返回一个代理(某个对象,具有用于加载实际实体的丰富方法的所谓代理").因此,这是在LazyLoading的帮助下实现的.

GetReference() does not load the entity immediately. A proxy( a certain object, a so called "deputy" with enriched methods for loading the actual entity) is returned. So it is a realisation with help of LazyLoading.

仅当需要/称为代理或其他持久性方法的属性时,代理才会交互并从数据库中加载实际实体.

Only if the attributes of the proxy or other persistence methods are needed/called the proxy interacts and loads the actual entity from the database.

例如:

User us = em.find(User.class, 70992);

GetReference()的用法与此类似.

GetReference() is used similarly.

 User us = em.getReference(User.class, 70922);

如果在持久化上下文中未知用户ID的实体,则将抛出EntityNotFoundException().

If the entity for the user id is not known in the persistence context, an EntityNotFoundException() is thrown.

当我不需要访问数据库状态时,我通常使用getReference方法(我的意思是getter方法).只是为了更改状态(我的意思是setter方法).

I usually use getReference method when i do not need to access database state (I mean getter method). Just to change state (I mean setter method).

在上述情况下,如果我想在获取用户后更新以下用户的年龄:

In above case if I want to update age of user like below after getting user:

setAge(age);

如果我调用find方法,那么JPA提供程序将在后台调用

If i call find method, JPA provider, behind the scenes, will call

SELECT NAME, AGE FROM USER WHERE USER_ID = ?

UPDATE USER SET AGE = ? WHERE USER_ID = ?

如果我调用getReference方法,那么JPA提供程序将在后台调用

If i call getReference method, JPA provider, behind the scenes, will call

UPDATE PERSON SET AGE = ? WHERE USER_ID = ?

由于调用getReference时,将获得一个代理对象.

Because when you call getReference, you will get a proxy object.

对于其他情况,我们必须像您所说的那样使用删除,持久和合并

For rest we have to use remove, persist and merge like you have said

这篇关于JPA从数据库创建,编辑和删除实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 17:27