简体   繁体   中英

spring crudrepository save with specific id

I want to insert(not update) data to my repository with specific id's, but whenever I do that Id's are ignored and the inserted entries have simply the next id in the sequence.

Entity entity = new Entity();
entity.setId(4l);
//..
Entity saved = repository.save(entity);
System.out.println(saved.getId()); // is 1l

Here's how my setup looks like

@Entity
@Table(name = "ENTITY")
public class Entity {

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

   //...

}

@Repository
public interface SomeRepository extends CrudRepository<Entity, Long> {

}

I also tried changing the generation strategy to AUTO but then I get

Table 'embedded-db.hibernate_sequence' doesn't exist

How can I insert data with specific ID while also allowing the id's to be generated?

UPDATE

Ok, so I found out that one of the solutions is forcing to use a specific sequence for generating the id and using generation strategy AUTO like this:

@Id
@Column(name = "ID")
@GeneratedValue(strategy=GenerationType.AUTO, generator="my_seq_gen")
@SequenceGenerator(name="my_seq_gen", sequenceName="actual_seq_name")
private Long id;

However I use mariaDb for my test env and it does not support sequences, so this solution does not work for me. Is there any other way to do this?

You're getting the error because AUTO means the JPA implementation will:

...pick an appropriate strategy for the particular database.

( Source )

Which, for the database you're using (not sure which one?), means hibernate looks in a pre-defined table for the next ID value to use.

As you are setting the IDs manually, remove the @GeneratedValue annotation from your variable.

I think you can use the parent and child class to support this function. You defined a abstract class with the no id member class, and have the two JPA child class, those map to the same table, but the id strategy is different. So in your code, when you want to set the id , you can use the no @GeneratedValue one. And the other one with @GeneratedValue can support the auto increment case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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