EntityManager persist() method does not insert record to database

前端 未结 9 943
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 11:52

I have problem with using EntityManager.persist(Object) method. Now when i get rid of other problems, by app work without Exception but object is not put in my data

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 12:31

    You will need to assign id generation strategy as below:

    @Entity
    @Table(name ="Chain")
    public class Chain implements Serializable{
    
    @Id
    @Column(name = "id")
        @GeneratedValue(strategy=GenerationType.IDENTITY)
      private Long id;
    @Column(name = "date")
      private Date date;
    @Column(name = "name")
      private String name;
    //setters and getters
    }
    

    and in save method

      public int saveChain(Chain chain) {
            chain.setDate(new Date());
          //chain.setId((long)44);  remove this line
            Boolean a;
            em.persist(chain);
    
            return 222;
        }
    

    if you assign Id, then hibernate/jpa will try to update record, which is not available, instead of inserting new record and I think will not throw exception.

提交回复
热议问题