简体   繁体   English

休眠:以一对一关系获取对象时返回null

[英]Hibernate: returning null when getting the object in a one to one relation

Whenever I try to get the joined object it is returning null. 每当我尝试获取联接的对象时,它都将返回null。 Sample code below: 下面的示例代码:

Table A 表A

id
name
b_id

Table B 表B

id
name

Coding 编码

@Entity
@Table(name = "A")
public class A {
    private Integer id;
    @OneToOne
    @JoinColumn(name = "b_id", nullable = false)
    private B b;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getId() {
        return id;
    }

    public B getb() {        
        return b;
    }
}

@Entity
@Table(name = "B")
public class B {
    private Integer id;
    private String name;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getId() {
        return id;
    }

    public String getname() {        
        return name;
    }
}

When I use getA(id).getB() function it returns null. 当我使用getA(id).getB()函数时,它返回null。 When I use getA it returns a valid object and not null. 当我使用getA它返回一个有效的对象,而不是null。

You have to move your @Id and @GeneratedValue(strategy = GenerationType.IDENTITY) and placed above your id variable like this. 您必须移动@Id和@GeneratedValue(strategy = GenerationType.IDENTITY)并像这样放置在id变量上方。

@Entity
@Table(name = "A")

public class A{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToOne
@JoinColumn(name = "b_id", nullable = false)
private B b;

public Integer getId() {
    return id;
}

public B getb() {

    return b;
}
}

Hope this will help. 希望这会有所帮助。

可能是您应该在joinColumn批注中将FetchType设置为Eager,以在加载a时也加载对象B。

You could consider use more annotation properties, for example: 您可以考虑使用更多注释属性,例如:

@OneToOne(cascade = CascadeType.ALL)
@JoinColum(name = "b_id" referencedColumnName = "id", nullable = false)
private B b;
@Entity
@Table(name = "B")

public class B{
**@Column(name="b_id", nullable=false)**
private Integer id;
private String name;


@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)

public Integer getId() {
    return id;
}

public String getname() {

    return name;
}
}

Use @Column(name="b_id", nullable=false) 使用@Column(name =“ b_id”,nullable = false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM