java 使用提供的 ID 使用 Hibernate 保存新对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4047175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:32:39  来源:igfitidea点击:

Save new object with Hibernate using supplied ID

javahibernatesession

提问by iryndin

I want to save some Objects to database with predefined IDs using Hibernate. Is it possible to do it using save method of Hibernate session?

我想使用 Hibernate 将一些对象保存到具有预定义 ID 的数据库中。是否可以使用 Hibernate 会话的保存方法来做到这一点?

I know there are following workarounds:

我知道有以下解决方法:

1) execute SQL script with necessary insert statements:

1) 使用必要的插入语句执行 SQL 脚本:

insert into MyObj(id,name) values (100,'aaa'), (101,'bbb');

2) use SQL query in Hibernate:

2)在Hibernate中使用SQL查询:

public static boolean createObj(Long id, String name) {
  Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  if (session.get(MyObj.class, id) == null) {        
    session.beginTransaction();
    SQLQuery sqlQuery = session.createSQLQuery
      ("insert into myobj(id,name) values(?,?)");
    sqlQuery.setLong(0, id);
    sqlQuery.setString(1, name);
    sqlQuery.executeUpdate();
    session.getTransaction().commit();
    return true;
  } else {
    return false;
  }
}

But: is it possible to do without SQLQuery?

但是:可以不用 SQLQuery 吗?

In Hibernate reference in section 11.2. Making objects persistentthere is example of code:

在第11.2节中的 Hibernate 参考中使对象持久化有代码示例:

Alternatively, you can assign the identifier using an overloaded version of save().

或者,您可以使用重载版本的 save() 分配标识符。

DomesticCat pk = new DomesticCat();
pk.setColor(Color.TABBY);
pk.setSex('F');
pk.setName("PK");
pk.setKittens( new HashSet() );
pk.addKitten(fritz);
sess.save( pk, new Long(1234) );

But I couldn't find example of how to do this.

但我找不到如何做到这一点的例子。

So, is it possible to save new objects with supplied IDs to database with Hibernate not using SQL query? If yes then how? And how to overload session method save() as mentioned in Hibernate reference?

那么,是否可以使用不使用 SQL 查询的 Hibernate 将具有提供的 ID 的新对象保存到数据库中?如果是,那么如何?以及如何重载 Hibernate 参考中提到的会话方法 save() ?

Thanks!

谢谢!

采纳答案by Binil Thomas

The documentation asks you not to override saveyourself, but to use the variant of savewhich takes two arguments. See the [JavaDocs][1] for more details.

该文档要求您不要覆盖save自己,而是使用save带有两个参数的变体。有关更多详细信息,请参阅 [JavaDocs][1]。

YourEntity entity = // ..
entity.setFoo(foo);
entity.setBar(bar);
//..
session.save(entity, theIDYouWantToUse);

[1]: http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Session.html#save(java.lang.String, java.lang.Object)

[1]:http: //docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Session.html#save(java.lang.String, java.lang.Object)

回答by alkimisticus

Use session.replicate

使用 session.replicate

YourEntity entity = // ..
entity.setId(yourId);
entity.setBar(bar);
//..
session.replicate(entity,ReplicationMode.EXCEPTION);

回答by Thomas W

Specify assignedas the generator on the ID column.

指定assigned为 ID 列上的生成器。

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html#mapping-declaration-id-generator

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html#mapping-declaration-id-generator

Note that for this to perform well, it helps to have a nullable version property. Hibernate then treats 'null' version values as being unsaved.

请注意,为了使其性能良好,拥有一个空的版本属性会有所帮助。Hibernate 然后将“空”版本值视为未保存。

<id name="id" type="int">
    <generator class="assigned" />
</id>
<version name="version" type="int">

public class Person {
    // ID;    assigned, SPEC.
    public int getId();
    public void setId (int id);
    // Version;  NOTE -- must be nullable!
    public Integer getVersion();
    public void setVersion (Integer version);
}

Hope this helps.

希望这可以帮助。

回答by Christian Gürtler

For now replicate(Object object, ReplicationMode replicationMode)seems to be an acceptable and the preferred way. You may want to play a little with the different values for ReplicationModeto suit your needs.

目前replicate(Object object, ReplicationMode replicationMode)似乎是一种可以接受和首选的方式。您可能想使用不同的值ReplicationMode来满足您的需要。

回答by Vinit Bhardwaj

Use save method of hibernate:- save(String entityName,Object object) For more information kindly follow:- http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Session.html#save(java.lang.String, java.lang.Object)

使用休眠的保存方法:- save(String entityName,Object object) 有关更多信息,请遵循:- http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Session.html#save( java.lang.String, java.lang.Object)

Note:- Do not use GeneratedValue of any type on above of your Primary key @GeneratedValue(strategy=GenerationType.IDENTITY)

注意:- 不要在主键 @GeneratedValue(strategy=GenerationType.IDENTITY) 上面使用任何类型的 GeneratedValue