如果不存在JPA插入对象,如果存在则不执行任何操作

时间:2016-08-18 18:39:49

标签: java jpa cascade

@Entity
@Table(name="PROPERTY_VALUES")
public class PropertyValuesData extends AbstractData {

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

    @OneToOne(fetch = FetchType.EAGER, cascade=  {CascadeType.PERSIST} )
    @JoinColumn(name = "VAL_PROP_ID")
    private PropertyData property;

}

持久对象:

  public void createItem(TYPE item){
            try{
                em=EMFactory.createEntityManager();
                em.getTransaction().begin();
                em.persist(item);
                em.getTransaction().commit();
            }catch(Exception e){
                logger.error("Error while createItem", e);
                System.err.println(e.getMessage());
            }finally {
                if(em!=null)
                    em.close();
            }
        }

我有两种情况: 1)我创建了新对象PropertyValuesData,其中包含现有属性(带有id) - >那么我只想添加新的PropertyValuesData 2)我使用新属性创建新对象PropertyValuesData - >然后我想插入新的PropertyData

如果我添加CascadeType.PERSIST,那么我可以保存新属性,但对于现有属性,请尝试再次插入。我应该怎么做以避免再次插入相同的属性?

1 个答案:

答案 0 :(得分:0)

Try adding additional CascadeType.MERGE

Also, remember that PropertyData needs to be Managed (so in current persistance context, and not detached) in order for it to work. If you use Detached entity, sets it id to something from the db, this will result can result in INSERT not UPDATE.

To get it working 100%, simply SELECT required PropertyData from the db (even by id just like you are trying, set it, and then persist PropertyValuesData