我们在JPA中声明了一些这样的表:
@Entity
@Table(name = "A")
public class A {
public A() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "a")
private Set<B> bs = new HashSet<>();
}
@Entity
@Table(name = "b")
public class B {
public B() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "a_id", foreignKey = @ForeignKey(name = "FK_B_A"))
private A a;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "c_id", foreignKey = @ForeignKey(name = "FK_B_C"))
private C c;
}
@Entity
@Table(name = "C")
public class C {
public C() {
}
@Id
@Column(name = "id")
private long id;
}
现在我想在表格中插入一些记录,我们知道c_id的值是1,我们想在B中插入一条记录而不从C中选择。
我们现在编写此代码:
a = aRepository.find(a_id);
b = new B();
b.setCId(1);
a.setBs(b);
aRepository.save(a);
但JPA,在插入记录之前,在C上执行选择并通过id == 1从c获取所有记录,如何拒绝此选择并告诉JPA只插入而不选择?
控制台日志记录如下:
""2018-02-06 16:08:44 -
select
...
from
c c_
where
c_.id=?
""2018-02-06 16:08:44 -
insert
into
b
(id, c_id, a_id)
values
(null, ?, ?)
答案 0 :(得分:2)
使用id
设置C调用getReference(例如JpaRepository中的getOne)a = aRepository.find(a_id);
b = new B();
C c = cRepository.getOne(1)
b.setC(c);
a.setBs(b);
aRepository.save(a);
使用getReference aka getOne将没有SQL语句,它只会创建一个可以分配给的代理对象。