简体   繁体   中英

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. Sample code below:

Table A

id
name
b_id

Table 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. When I use getA it returns a valid object and not null.

You have to move your @Id and @GeneratedValue(strategy = GenerationType.IDENTITY) and placed above your id variable like this.

@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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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