@OneToMany在子表的外键中填充NULL

时间:2018-07-26 05:03:35

标签: hibernate jpa

我已经创建了一个用户obj和Post对象。然后,我用post对象填充用户对象。最后,我只保存了User对象。我只保存用户,希望帖子可以在内部保存。

我搜索了解决方案,但是人们分别保存了对象。我不想那样。

我的实体类,

@Entity
public class User {

    @Id
    @GeneratedValue
    private Integer userId;
    @Column(name = "uname")
    private String userName;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Post> post;

    //Getters and Setters
}


@Entity
public class Post {

    @Id
    @GeneratedValue
    private Integer postId;
    private String description;

    @ManyToOne
    @JoinColumn(name = "userId")
    User user;

    //Getters and Setters
}

我正在尝试以下。

主要方法:

public static void main(String... a) {

    String userName = "", description = "";
    int userId = 14, postId = 12;
    List<Post> posts = new ArrayList<>();

    int postNo = 25;
    userName = "User " + postNo;
    posts.add(new Post(postNo + "th Post by " + userName));
    insertUserAndPost(userName, posts);
}



private static void insertUserAndPost(String userName, List<Post> posts) {
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    System.out.println("Saving User, Post should get saved automatically!");
    User user = new User();
    user.setUserName(userName);

    user.setPost(posts);

    Serializable id = session.save(user);
    session.getTransaction().commit();
    displayUser(Integer.parseInt(id.toString()));

}

数据库结果:

User:

|     24 | Abdul 22     |

Post:

|     16 | 22th Post by User 22 |   NULL |

为什么在NULL表中已将NULL插入到外键中? 请帮助

0 个答案:

没有答案