0

I search a way to create a primary key with two values.

I need to get the current year add it to a sequence (this sequence need to be restarted at the beginning of every year.

For 2018

First record: 20181
Second record: 20182

For 2019

First record: 20191

I was thinking to use embededid who include a sequence that I would reset every year.

Edit

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Cars {

    @EmbeddedId
    private EmbedddedCarsKey id;

}

@Embeddable
public class EmbedddedCarsKey implements Serializable {

    private int year;

    @SequenceGenerator(name = "cars_id_seq", sequenceName = "cars_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cars_id_seq")
    private Integer seq

    public EmbedddedCarsKey();
      year = LocalDate.now().getYear();
    }

}

When I try to save I get

Cars cars = new Cars();
cars.setName("Honda");

carsRepository.save(cars);

org.hibernate.id.IdentifierGenerationException: null id generated for:class com.ush.mcl.model.Cars

Edit 2

tried that...

cars = new Cars
EmbedddedCarsKey key= new EmbedddedCarsKey();
cars.setId(key);

but seq value stay null;

Yvan Dupré
  • 51
  • 2
  • 10

0 Answers0