Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 824
Ben Avatar asked Nov 07 '25 10:11

Ben


2 Answers

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.

like image 87
Catchwa Avatar answered Nov 10 '25 02:11

Catchwa


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.

like image 35
fartpig Avatar answered Nov 10 '25 02:11

fartpig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!