Hello stackoverflow社区。 p>
我想知道,如果OpenJPA中有可能在插入之前首先检查对象是否已存在于数据库中。
我有两个分支:
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;
}
如果我想添加新的播放器或团队,JPA应首先检查此播放器或团队是否已在数据库中。 如果是,那么它应该使用现有单元的主/外键。
这可能吗?或者我需要编写自己的方法吗?
最诚挚的问候 Veote
答案 0 :(得分:1)
您可能需要检查此开关: http://openjpa.apache.org/builds/2.2.0/apache-openjpa/docs/jpa_2.2.html#jpa_2.2_cascadePersist
我猜您使用的是OpenJPA 2.2.0。
答案 1 :(得分:0)
public interface EntityManager {
/**
* Make an instance managed and persistent.
* @param entity
* @throws EntityExistsException if the entity already exists.
* (If the entity already exists, the EntityExistsException may
* be thrown when the persist operation is invoked, or the
* EntityExistsException or another PersistenceException may be
* thrown at flush or commit time.)
* @throws IllegalArgumentException if the instance is not an
* entity
* @throws TransactionRequiredException if invoked on a
* container-managed entity manager of type
* PersistenceContextType.TRANSACTION and there is
* no transaction
*/
public void persist(Object entity);
. . .
}
如果您调用EntityManager.persist(...)并传入DB中已存在的Player实例,则JPA(根据规范)将抛出EntityExistsException。我建议您阅读EntityManager javadoc,以便更好地了解您可以使用API执行的操作。另外,我建议在实体中添加@Version字段。
答案 2 :(得分:-1)