How to initialize schema in spring-session with JDBC

Viewed 9870

I'm using Spring Boot 2.0.x, Hibernate and Spring Session Jdbc with Mysql 5.7. I'm working under development environment, so Hibernate is configured to generate schemas every time:

spring.jpa.hibernate.ddl-auto=create-drop

And it works fine, but I have a problem with Spring Session... I tried set initialize-schema, but it doesn't work.

spring.session.jdbc.initialize-schema=always

Is it possible to auto generate full schema (all entities and SPRING_SESSION)?

It doesn't work for me with MySQL and H2 (I tried embedded option)

2 Answers

I am describing the steps.It worked for me.

1- Add the dependency in your pom file.

<dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-jdbc</artifactId>
    </dependency>

2-Add the sql file in your project with same path and same name Under "resources" file.

PATH : /org/springframework/session/jdbc/schema-mysql.sql

schema-mysql.sql

CREATE TABLE SPRING_SESSION (
    PRIMARY_ID CHAR(36) NOT NULL,
    SESSION_ID CHAR(36) NOT NULL,
    CREATION_TIME BIGINT NOT NULL,
    LAST_ACCESS_TIME BIGINT NOT NULL,
    MAX_INACTIVE_INTERVAL INT NOT NULL,
    EXPIRY_TIME BIGINT NOT NULL,
    PRINCIPAL_NAME VARCHAR(100),
    CONSTRAINT SPRING_SESSION_PK PRIMARY KEY (PRIMARY_ID)
) ENGINE=InnoDB ROW_FORMAT=DYNAMIC;

CREATE UNIQUE INDEX SPRING_SESSION_IX1 ON SPRING_SESSION (SESSION_ID);
CREATE INDEX SPRING_SESSION_IX2 ON SPRING_SESSION (EXPIRY_TIME);
CREATE INDEX SPRING_SESSION_IX3 ON SPRING_SESSION (PRINCIPAL_NAME);

CREATE TABLE SPRING_SESSION_ATTRIBUTES (
    SESSION_PRIMARY_ID CHAR(36) NOT NULL,
    ATTRIBUTE_NAME VARCHAR(200) NOT NULL,
    ATTRIBUTE_BYTES BLOB NOT NULL,
    CONSTRAINT SPRING_SESSION_ATTRIBUTES_PK PRIMARY KEY (SESSION_PRIMARY_ID, ATTRIBUTE_NAME),
    CONSTRAINT SPRING_SESSION_ATTRIBUTES_FK FOREIGN KEY (SESSION_PRIMARY_ID) REFERENCES SPRING_SESSION(PRIMARY_ID) ON DELETE CASCADE
) ENGINE=InnoDB ROW_FORMAT=DYNAMIC;

I got the sql file from official spring github account.

https://github.com/spring-projects/spring-session/blob/master/spring-session-jdbc/src/main/resources/org/springframework/session/jdbc/schema-mysql.sql

3-Add below properties into application.properties

spring.session.jdbc.initialize-schema=always
spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/schema-mysql.sql

If it don't work again,please let me know.Like I said,It worked for me. enter image description here

Try this setting in the application.properties

spring.session.store-type=jdbc
spring.session.jdbc.initialize-schema=always //spring will create required tables for us
spring.session.timeout.seconds=900
Related