Search code examples
javajpaopenjpa

Apache OpenJPA - Inserting tuple only if not exists in database


Hello stackoverflow community.

I want to know, if there is a possibility in OpenJPA to check first if the object already exists in DB before inserting.

I have two clases:

imports...

@Entity(name="Player")
public class Player {
    private long id;
    private String nickName;
    private Team team; /* A Player is on a Team */

    @ManyToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name = "team_id")
    public Team getTeam() {
        return team;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public long getId() {
        return id;
    }

    /* more getters / setters ...*/
}
@Entity(name="Team")
public class Team {
    private long id;
    private String name;
    private List<Player> players; /* A Team Has Players */

    @OneToMany(mappedBy = "team", targetEntity = Player.class, 
            fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
    public List<Player> getPlayers() {
        return players;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public long getId() {
        return id;
    }

If I want to add a new Player or Team, JPA should check first if this Player or Team is already in the database. If yes, then it should use the primary / foreign key of existing unit.

Is this possible? Or do I need to write my own method?

Best Regards Veote


Solution

  • You may want to check this switch: http://openjpa.apache.org/builds/2.2.0/apache-openjpa/docs/jpa_2.2.html#jpa_2.2_cascadePersist

    I guess that you are using OpenJPA 2.2.0.