Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid having JPA to automatically persist objects

Tags:

java

spring

jpa

Is there any way to avoid having JPA to automatically persist objects?

I need to use a third party API and I have to pull/push from data from/to it. I've got a class responsible to interface 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 UserJpa class looks like:

@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 the method (e.g. pullUser(1)), the returned user is automatically stored in the database. I don't want this to happen, is there a solution to avoid it? I know a solution could be to create a new class implementing User and return an instance of this class in the pullUser() method, is this a good practice?

Thank you.

like image 823
satoshi Avatar asked Sep 01 '26 16:09

satoshi


1 Answers

Newly create instance of UserJpa is not persisted in pullUser. I assume also that there is not some odd implementation in getUserDataFromApi actually persisting something for same id.

In your case entity manager knows nothing about new instance of UserJPA. Generally entities are persisted via merge/persist calls or as a result of cascaded merge/persist operation. Check for these elsewhere in code base.

like image 198
Mikko Maunu Avatar answered Sep 04 '26 07:09

Mikko Maunu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!