简体   繁体   中英

How to add primary key using data.sql in spring boot with hibernate enhanced sequence generator strategy

i have a project where i'm trying to add values from data.sql file, problem is i don't know how to add primary key with hibernate enhanced sequence strategy.

I tried to do that without adding values of primary keys, thinking it will do it automatically, but error, then i tried to use like a AUTO_INCREMENT primary key, but that results in errors tho... what can i do?

So i have a Hibernate generator for id's:

@org.hibernate.annotations.GenericGenerator(
        name = "STORE_ID_GENERATOR", strategy = "enhanced-sequence",
        parameters =
                {
                        @org.hibernate.annotations.Parameter(name = "sequence_name", value = "HIBERNATE_STORE_SEQUENCE"),
                        @org.hibernate.annotations.Parameter(name = "initial_value", value = "1")

An Entity which use this generator id:

    @Entity
    public class Store {
    
        @Id
        @GeneratedValue(generator = "STORE_ID_GENERATOR") //pre insert added values on id
        @Column(name = "STORE_ID", unique = true, updatable = false)
        private Long storeId;
                

Schema.sql file:

create table PROJECT_HIBERNATE_Store (STORE_ID bigint not null, STORE_LOCATION_CITY varchar(255), STORE_LOCATION_COUNTRY varchar(255), STORE_LOCATION_ZIPCODE varchar(255), storeName varchar(255), storeType varchar(255), PROMOTION_STORE_ID bigint,  PRIMARY KEY AUTO_INCREMENT (STORE_ID) bigint);

// i don't know wot to add primary key here...

// and how to use it here...

data.sql file:

INSERT INTO PROJECT_HIBERNATE_Store (STORE_LOCATION_CITY, STORE_LOCATION_COUNTRY, STORE_LOCATION_ZIPCODE,
                                     storeName, storeType, STORE_ID) values ('Sudava', 'America', '12341431', 'Catena', 'MEDICAL_STORE', 'hibernate_sequence.nextval');

Your schema.sql is creating a PK that is auto incremented so the DB not hibernate will be responsible for populating the STORE_ID column

Rather than using a sequence you can set your id strategy to IDENTIY

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

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