防止实体在JPA中窃取彼此的映射子实体

时间:2019-04-06 16:37:31

标签: java hibernate spring-boot jpa persistence

我有两个实体,主题课程。主题与Lesson具有OneToMany关系。

我的数据库已经有2组对象:

X

final ReadWriteLock rwl = new ReentrantReadWriteLock();

public boolean transferMoney(Account from, Account to, int amount) {
  rwl.readLock().lock();
  try{
    .... Your current code here
  }
  finally {
       rwl.readLock().unlock();
  }
}

public int sumAccounts(List<Account> accounts) {
  rwl.writeLock().lock();
  try{
    // You dont need atomic integer here, because this can be executed by one thread at a time
    int sum = 0;
    for (Account a : accounts) {
        sum += a.getBalance();
    }
    return sum;
  }
  finally {
       rwl.writeLock().unlock();
  }
}

实体定义如下

{
    "id": 1,
    "name": "wow",
    "lessons": [
        {
            "id": 2,
            "difficulty": "hard"
        }
    ]
}

由于该对象正在窃取(1,“哇”)课,因此我想防止该对象成功保存:

{
    "id": 3,
    "name": "wow2",
    "lessons": [
        {
            "id": 4,
            "difficulty": "hardy"
        }
    ]
}

手动迭代所有课程是一种显而易见的方法,但是我想要一个简单的解决方案。

编辑: 我的解决方案解决了盗窃问题,但是也创建了另一个问题

@Entity
public class Lesson {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    private String difficulty;

    @ManyToOne(targetEntity = Subject.class)
    private Subject subject;
}

@Entity
public class Subject {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    private String name;

    @OneToMany(orphanRemoval=false, cascade= CascadeType.ALL)
    @JoinColumn(name = "subject_id")
    private List<Lesson> lessons;
}

这可以解决盗窃问题,但是如果我想从主题中取消课程,可以删除孤儿。

{ "id": 3, "name": "wow2", "lessons": [ { "id": 2, "difficulty": "hard_overrriden" } ] } 删除后,它只是停止与主题取消关联。

解除关联对象如下:

@ManyToOne
@JoinColumn(updatable = false)
private Subject subject;
.
.
.
@OneToMany(cascade= CascadeType.ALL, mappedBy="subject", orphanRemoval=true)
private List<Lesson> lessons;

0 个答案:

没有答案