Spring Hibernate使用hibernate模板在Foreign key列中插入一对多的null

时间:2017-08-23 07:06:32

标签: hibernate spring-mvc

我已经实现了一对多关系(注释),如下所示:

// 用户类

@Entity
@Table(name="user")
public class User {

    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private Integer id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    @Column(name="email_id")
    private String emailId;

    @Column(name="password")
    private String password;

    @OneToMany(targetEntity=Address.class,cascade=CascadeType.ALL)
    @JoinColumn(name="user_id", referencedColumnName="id")
    private List<Address> addresses;

    ..... setters and getters
 }

// 地址类

    @Entity
    @Table(name="address")
    public class Address {

        @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name="add_id")
        private Integer addId;

        @Column(name="pin_code")
        private String pinCode;

        @Column(name="street")
        private String street;

        @Column(name="city")
        private String city;

        @Column(name="state")
        private String state;

        ... setters and getters

    }

问题在于,当我使用hibernate模板保存用户对象(其中还包含一个地址对象的列表)时,它正在插入 null 地址表中的外键列(&#34; user_id&#34;)。

它会为两个表触发 2个插入语句,但不触发更新语句来更新外键列

但是当我使用 SessionFactory 时,它按预期工作(下面是会话工厂的代码):

    SessionFactory factory = template.getSessionFactory();
    Session session = factory.openSession();

    Transaction transaction = session.beginTransaction();       

    try{
        //id = (Integer) template.save(user);
        id = (Integer) session.save(user);
    }catch(Exception e){
        System.out.println(e);
        id = -1;
    }

    transaction.commit();
    session.close();

在上述情况下,它会激活 2 insert和1 update 来更新外键列

1 个答案:

答案 0 :(得分:0)

请查看以下地图

<强> User.java

@Entity
@Table(name="user")
public class User {

@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Integer id;

@Fetch(value = FetchMode.SELECT)
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "id")
@JsonIgnore 
private List<Address> addressList ;

//remaining fields and getter setters here
}

<强> Address.java

@Entity
@Table(name="address")
public class Address {

    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="add_id")
    private Integer addId;


   @ManyToOne
   @JoinColumn(name = "id", insertable = true, updatable = true, nullable = true)
   private User user;

//remaining fields and getter setters here
}