在插入JPA之前忽略选择



我们在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中获取所有记录,我该如何拒绝此选择并告诉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, ?, ?)

设置c呼叫getReference(例如,jparepository in jparepository中的getOne(,具有ID

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语句,它将创建一个可以分配给A。

的代理对象

最新更新