Java JPA Hibernate保存不插入引用的实体

时间:2018-03-17 14:30:08

标签: java hibernate jpa

我有以下两个班级:

@Entity
@Table(name = "TableA")
public class EntityA
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private final Integer id = null;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "BId")
    private EntityB b;

    public EntityA(EntityB b)
    {
        this.b = b;
    }
}

@Entity
@Table(name = "TableB")
public class EntityB
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private final Integer id = null;

    @OneToOne(mappedBy = "b")
    private final EntityA a = null;
}

当我这样做时

session.save(new EntityA(new EntityB());

数据库仅在TableA中插入记录,并将引用TableB的列保留为NULL

如果我先插入b,那么a,它可以工作,但它也应该只需一次调用。

其他问题/答案提到注释不正确,但我认为我和提供的解决方案没有区别。

我也尝试在@OneToOne注释上添加CascadeType.PERSIST,但这也没有用。

2 个答案:

答案 0 :(得分:0)

在jpa中,默认级联设置为NONE ...因此默认情况下不会插入(持久化)关系中的实体(在您的情况下为B)...您需要注释与之关系     @OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.PERSIST)

答案 1 :(得分:0)

首先,您必须从实体中删除最终关键字。 试试这个:

@Entity
@Table(name = "TableA")
class EntityA {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private Integer id;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumn(name = "BId")
    private EntityB b;


    public Integer getId() {
        return id;
    }


    public void setId(Integer id) {
        this.id = id;
    }


    public EntityB getB() {
        return b;
    }


    public void setB(EntityB b) {
        this.b = b;
    }


    public EntityA(EntityB b) {
        this.b = b;
        b.setA(this);
    }
}

@Entity
@Table(name = "TableB")
class EntityB {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private Integer id;

    @OneToOne(mappedBy = "b")
    private EntityA a;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public EntityA getA() {
        return a;
    }

    public void setA(EntityA a) {
        this.a = a;
    }
}

我正在使用spring boot,hibernate和H2数据库

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext app =  SpringApplication.run(DemoApplication.class, args);
        ServiceCascade bean = app.getBean(ServiceCascade.class);
        bean.save();
    }
}

@Service
class ServiceCascade {
    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public void save() {
        EntityA entityA = new EntityA(new EntityB());
        entityManager.persist(entityA);
    }
}

以下日志显示正确插入了两个实体

org.hibernate.SQL : insert into tableb (id) values (null)
org.hibernate.SQL : insert into tablea (id, bid) values (null, ?)
o.h.type.descriptor.sql.BasicBinder  : binding parameter [1] as [INTEGER] - [1]