Spring JPA how to make sure that data gets written into persistent storage

后端 未结 1 526
清歌不尽
清歌不尽 2021-01-27 03:55

I am trying to extend this example: https://github.com/scratches/jpa-method-security-sample by adding a method in the controller to \"signup\" where a new user is dynamically ad

1条回答
  •  伪装坚强ぢ
    2021-01-27 04:24

    Since you're using an embedded in-memory H2 database data does not persist across restarts. You should move away from the embedded DB, and since the app is based on spring-boot, you can easily reconfigure this and use e.g. mysql, by adding mysql dependency to the pom.

        
            mysql
            mysql-connector-java
        
    

    and appropriate DB properties inside application.properties e.g.

    spring.datasource.url=jdbc:mysql://localhost/[YOUR DB]
    spring.datasource.username=[YOUR USERNAME]
    spring.datasource.password=[YOUR PASSWORD]
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    

    Another thing to keep in mind, certain defaults are specific for embedded DBs such as the H2 DB. For example, the ddl-auto property is set to create-drop.

    This means that the DB schema will be created when the SessionFactory is created and dropped when it is closed.

    The value of this property for e.g. MySql is set to none by default, this means that you'll have to initially run your application overriding the property (settting it inside application.properties)

    spring.jpa.hibernate.ddl-auto: create
    

    this will initially create the data from the import.sql. After the first start, change the property to update, and you'll data will persist across restart

    0 讨论(0)
提交回复
热议问题