简体   繁体   English

休眠:在以下情况下插入具有自定义ID的实体:strategy = GenerationType.AUTO

[英]Hibernate: inserting an entity with custom id in the case: strategy = GenerationType.AUTO

Hib just ignoring an id setting if that strategy take a place. Hib只是忽略了ID设置(如果采用该策略)。

Are there any ways to avoid that and save the strategy? 有什么方法可以避免这种情况并保存策略吗?

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
public Long getId() {
     return id;
}

... ...

Account account = new Account();
account.setId(1000L);
account.setSmth(smth);
...
//Tried to do so, but tomcat hangs on this string. 
session.createSQLQuery("ALTER TABLE account AUTO_INCREMENT = " + account.getId() + ";").executeUpdate();
session.save(account);
...

Spasibo! Spasibo!

just remove the annotation of GeneratedValue as below, then entity will use the asssigned id value. 只需删除GeneratedValue的注释,如下所示,则实体将使用分配的ID值。 it works in my webapp. 它可以在我的webapp中使用。

@GeneratedValue(strategy = GenerationType.AUTO)

You can store entities with assigned id if necessary using this strategy: 您可以使用以下策略存储具有指定ID的实体:

@GeneratedValue(strategy="org.hibernate.id.Assigned")
public Long getId() {
    ...
}

The only drawback is that you have to include a version field that Hibernate needs to recognize if it is a new or an existing entity: 唯一的缺点是您必须包括一个Hibernate需要识别的版本字段,无论它是新实体还是现有实体:

@Version
public Long getVersion() {
    ...
}

remove the annotation @GeneratedValue. 删除注释@GeneratedValue。 Hibernate will use the identifier you assigned. Hibernate将使用您分配的标识符。 please see below description coming from Hibernate document. 请参见以下来自Hibernate文档的描述。

assigned 已分配

lets the application assign an identifier to the object before save() is called. 让应用程序在调用save()之前为对象分配一个标识符。 This is the default strategy if no element is specified. 如果未指定任何元素,则这是默认策略。

refer to https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html 请参阅https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM