Hibernate Save Object without one column

扶醉桌前 提交于 2020-01-06 02:20:54

问题


I have a table called test and It has columns like id, name, address. I have created POJO class(User) for all the three columns and same has been mapped with hbm configuration.

Here My questions is, How do I prevent one column while saving the User object in session (session.save(User)).

Let say I dont want to save my address field. How can I prevent. Are there any properties in HIbernate configuration or any modifier needs to be added in POJO?


回答1:


Make that field as Transient.

Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).

https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html




回答2:


  • If you're using annotations config you could could do as follows,

    import javax.persistence.Transient;
     ....
    Class User{
      @Transient
      private String address;
      ....
    
  • If you're using xml configuration just avoid creating a mapping to address propery in the hibernate.cfg.xml file. Unmapped properties are not saved by hibernate.

Hope this helps.




回答3:


In order to avoid a field from an entity to be persisted in DB one can use one of the two mechanisms:

@Transient - the JPA annotation marking a field as not persistable

transient keyword in java. Beware - using this keyword, will prevent the field to be used with any serialization mechanism from java. So, if the field must be serialized you'd better use just the @Transient annotation.



来源:https://stackoverflow.com/questions/34106951/hibernate-save-object-without-one-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!