arctica
arctica

Reputation: 346

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.

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!

Upvotes: 2

Views: 5807

Answers (3)

Guanguan
Guanguan

Reputation: 47

remove the annotation @GeneratedValue. Hibernate will use the identifier you assigned. please see below description coming from Hibernate document.

assigned

lets the application assign an identifier to the object before save() is called. 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

Upvotes: 0

Henry Leu
Henry Leu

Reputation: 2274

just remove the annotation of GeneratedValue as below, then entity will use the asssigned id value. it works in my webapp.

@GeneratedValue(strategy = GenerationType.AUTO)

Upvotes: 1

You can store entities with assigned id if necessary using this strategy:

@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:

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

Upvotes: 1

Related Questions