与外键

时间:2018-03-12 10:33:23

标签: java spring hibernate jpa hibernate-mapping

所以我们有2个实体

@Entity
@Table(name = "block")
public class Block {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column
    private long id_block;
    @Column
    private String name;

    @OneToMany(mappedBy = "block",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    private List<Subblock> subblock = new ArrayList<>();

    /* getters and setters*/
}
@Entity
@Table(name = "subblock")
public class Subblock {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENT)
    @Column
    private long id_subblock;

    @ManyToOne
    @JoinColumn(name="id_block")
    private Block block;

    @Column
    String name;
    /* getters and setters*/
}

据我了解在表Subblock中获取id_block我需要链接父子和子父

Block block = new Block();
        Subblock subblock = new Subblock();
        List<Subblock>subblockList= new ArrayList();
        subblock.setName("subblock_1"));

        subblock.setBlock(block);/*child-parent*/

        subblockList.add(subblock);
        block.setName("block_1"));
        block.setSubblock(subblockList);/*parent-child*/

        try {
                ratingService.add(block);/*merge the block*/
        }
        catch (NullPointerException e){
            e.printStackTrace();
        }

在这种情况下,我在表Subblock到字段id_block中有正确的引用。

@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(
    private List<Subblock> subblock = new ArrayList<>();
@ManyToOne
        @JoinColumn(name="id_block")
        private Block block;

在这种情况下,我只是结果而没有链接子父母

Block block = new Block();
            Subblock subblock = new Subblock();
            List<Subblock>subblockList= new ArrayList();
            subblock.setName("subblock_1"));
            subblockList.add(subblock);
            block.setName("block_1"));
            block.setSubblock(subblockList);/*parent-child*/
            try {
                    ratingService.add(block);
            }
            catch (NullPointerException e){
                e.printStackTrace();
            }

那么正确的方法是什么?和案例2一样做是不是正确?

0 个答案:

没有答案