使用jpa从数据库中删除行

deleting rows from database using jpa

我有一个名为 ACCOUNT 的 table,它由 account_id、position_id 和其他几列组成。另一个 table 我有 PositionCombination,它由列 position_id 和更多列组成。

这是我

的帐户 class
@RooJavaBean
@RooToString
@RooJpaActiveRecord
@RooJpaEntity
public class Account {

@OneToMany(mappedBy="account", fetch=FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval=true)
List<PositionCombination> allPositions = new ArrayList<PositionCombination>();

@OneToMany(mappedBy="account", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
List<Message> messages = new ArrayList<Message>();

 /*@OneToMany(mappedBy="account", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
List<PremiumPlayPositionCombination> premiumPlayPosition = new ArrayList<PremiumPlayPositionCombination>();*/

@OneToMany(mappedBy="account", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
List<PositionCombinationArc> allPositionsArc = new ArrayList<PositionCombinationArc>();



@ManyToOne
@JoinColumn(name="user_id")
private Userr user;

public List<PositionCombination> getOrders() {
return null;
}



public List<PositionCombination> getPositions() {
return null;
}

}

这是 PositionCombinatin Class

package com.uforic.optionstrader.domain;

@RooJavaBean
@RooToString
@RooJpaEntity
@RooJpaActiveRecord(finders = { "findPositionCombinationsByOrderStatus", "findPositionCombinationsByAccount", "findPositionCombinationsByStrategyType" })
public class PositionCombination {

private int positionType;

/*
 * Strategy type = 1 - Short Term Exit
 * 2 - Calendar Exit
 * 3 - Intraday Exit
 * Currently undefined for normal exit
 */
@ManyToOne
@JoinColumn(name = "strategy_id")
private Strategy strategy;


@OneToMany(mappedBy = "positionCombination", targetEntity = AbstractPosition.class, cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.EAGER)
private List<AbstractPosition> positions = new ArrayList<AbstractPosition>();

@ManyToOne
@JoinColumn(name = "account_id")
private Account account;

@NotNull
int orderStatus;


/* 1 - Short term Exit
 * 2 - Calendar Exit 
 */
int strategyType;

@OneToMany(mappedBy="positionCombination", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
List<StrategyExitReport> exitReports = new ArrayList<StrategyExitReport>();

@OneToMany(mappedBy="positionCombination", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
List<StrategyExitTracker> exitTrackers = new ArrayList<StrategyExitTracker>();

@OneToMany(mappedBy="positionCombination", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
List<IntradayExitDecision> intradayExitDecisions = new ArrayList<IntradayExitDecision>();

@OneToMany(mappedBy="positionCombination", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
List<ExitDecision> exitDecisions = new ArrayList<ExitDecision>();

@OneToMany(mappedBy="positionCombination", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
List<Message> messages = new ArrayList<Message>();

public BigDecimal getTotalCostWithMarginPerContract() {
    BigDecimal totalCostWithMargin = BigDecimal.ZERO;
    for (AbstractPosition position : positions) {
        totalCostWithMargin = totalCostWithMargin.add(position.getTotalCostPerContract().add(position.getMarginAmount()));
    }
    return totalCostWithMargin;
}

public BigDecimal getTotalCostWithMargin() {
    BigDecimal totalCostWithMargin = BigDecimal.ZERO;
    for (AbstractPosition position : positions) {
        totalCostWithMargin = totalCostWithMargin.add(position.getTotalCostWithMargin());
    }
    return totalCostWithMargin;
}

public static Integer deletePositions(long accid) {
    return new PositionCombination().deletePositionCombinationByAccount(accid);
}

@Transactional
private Integer deletePositionCombinationByAccount(Long accountid) {
    System.out.println("acc id :" + accountid);
    EntityManager em = PositionCombination.entityManager();
    int result = em.createQuery("DELETE FROM PositionCombination o where o.account.id = :accountid").setParameter("accountid", accountid).executeUpdate();
    return result;
}

public static TypedQuery<PositionCombination> findPositionCombinationsByStrategyTypes(List strategyTypes) {
    EntityManager em = PositionCombination.entityManager();
    TypedQuery<PositionCombination> q = em.createQuery("SELECT o FROM PositionCombination AS o WHERE o.strategyType IN (:strategyTypes)", PositionCombination.class);
    q.setParameter("strategyTypes", strategyTypes);
    return q;
}

}

现在当我运行这段代码。它会从该特定帐户的 positionCombination Table 中删除所有 entereis。

public void createSquareOff(User user,Account acc)
{
 List<PositionCombination> positionCombinationList = acc.getAllPositions();
 positionCombinationList.clear();
 acc.persist();
}

但是当我将代码更改为此时。它不会从 PositionCombination table 中删除行。在这里,我只是做了一些小改动,而不是获取 AllPositions,我根据 position_id 从 DB 获取特定的 Positions 并将其存储到该 positionCombinationList.

 public void createSquareOff(User user,Account acc,PositionCombination posComb )
 {
  List<PositionCombination> positionCombinationList = PositionCombination.findPoscomByPoscombination(posComb);
  positionCombinationList.clear();
  acc.persist();
 }

两种方法的实现有很大的不同。

在第一个中,您从 Account 获取 allPositions 属性。然后从该关系中清除所有相关的 PositionCombination 实体。

考虑到 allPositions 属性用 @OneToMany 注释,参数如下:

orphanRemoval=true

它告诉 JPA 提供程序在从关系中删除相关实体时删除它们。这就是为什么当您清除 allPositions 属性时,所有相关的 PositionCombination 都会被删除。

在第二个实现中,您将执行 JPA 查询并将结果作为 ListList 不是实体属性,因此清除它不会影响数据库或实体状态。您必须明确删除这些实体。此外,您不再需要 Account 实例。