如何使用OneToMany双向关系

时间:2017-03-29 18:19:30

标签: hibernate

i am just learning how to work with oneToMany bidirectional relation. 

i came across the following issue.
While saving the parent Entity it is getting saved and child entity too. this is creating a column in the child table with name "fk_id". but it is not saving the foreign key value into it.can you guys help me out from this?


Entity class :
        public class TestEntity implements Serializable{
             @Id 
             @GeneratedValue(strategy = GenerationType.AUTO)
             @Column(name = "id")
             private int id;
             @OneToMany(mappedBy="testEntity",cascade=CascadeType.ALL)
             private List<TestEntityChild> testEntityChildList;
        }
        Child Class:
        @Entity
        @Table(name="testchild")
        public class TestEntityChild {
          @Id
          @GeneratedValue(strategy = GenerationType.AUTO)
          @Column(name="Test_id")
          private int testId;
          @ManyToOne
          @JoinColumn(name="fk_id")     
          private TestEntity testEntity;
        }

我们创建TestEntity的方式。我从邮递员那里消费这项服务。我以json格式提供{name,roll和stream}。

@POST
    @Path("v1/test")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    //(TestEntity testEntity
    public TestEntity test(TestEntity testEntity){
        System.out.println("test to hit the service");
        System.out.println("input string :"+testEntity.getName());
        LOGGER.info("Log4j implemented in the project");
        TestEntityChild obj=new TestEntityChild();
        TestEntityChild obj1=new TestEntityChild();
        obj.setCity("delhi1");
        obj.setState("bihar1");
        obj1.setCity("delhi2");
        obj1.setState("bihar2");
        List<TestEntityChild> list=new ArrayList();
        list.add(obj);
        list.add(obj1);
        testEntity.setTestEntityChildList(list);;
        homeCareDaoImp.doaProcess(testEntity);

将元素保存在DB中的代码:

  session=getSession();     
    trnx=session.beginTransaction();
    session.save(testEntity);
    session.flush();
    trnx.commit();

您能告诉我,为什么没有必要条件来实现Serializable到实体类。 提前谢谢!

0 个答案:

没有答案