Avoid JPA automatically save objects

Is there a way to prevent JPA from automatically saving objects?

I need to use a third-party API, and I have to pull / delete data from / to it. I have a class responsible for the API, and I have a method like this:

public User pullUser(int userId) {
    Map<String,String> userData = getUserDataFromApi(userId);
    return new UserJpa(userId, userData.get("name"));
}

Where the class is UserJpaas follows:

@Entity
@Table
public class UserJpa implements User
{
    @Id
    @Column(name = "id", nullable = false)
    private int id;

    @Column(name = "name", nullable = false, length = 20)
    private String name;

    public UserJpa() {
    }

    public UserJpa(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

When I call a method (e.g. pullUser(1)), the returned user is automatically stored in the database. I do not want this to happen, is there a solution to avoid this? I know that the solution may be to create a new class that implements Userand return an instance of this class in the method pullUser(), is this good practice?

Thank.

+3
source share
3 answers

UserJpa pullUser. , getUserDataFromApi - , - .

UserJPA. / /. .

+6

, JPA, EntityManager persist() merge(). , , persist, .

0

Typically, JPA objects are managed objects, these objects reflect their changes in the database, when the transaction completes and before that in the first level cache, it is obvious that these objects should be managed first.

I really think that the best practice is to use a DTO object to process data transfer, and then use the object only for persistence purposes, so it will be more cohesive and lower, these are not objects with their nose, it should not.

Hope this helps.

0
source

All Articles