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 added to the repo. The default set of existing users is added in the import.sql script. However, I see that my dynamically added user gets wiped out on server restart. Could you point me out the way to make sure the table gets updated persistently.
Here is my code for the signup method:
@RequestMapping(value = "signup",method = RequestMethod.GET)
public String signup(Map<String, Object> model) {
model.put("message","Sign up!");
model.put("title", "Hello Signup");
model.put("date", new Date());
users.createUser();
return "signup";
}
public void createUser() {
User u = new User();
u.setName("xxx");
u.setPassword("spring");
repo.save(u);
}
I have also made changes to loadUserByUserName
to return the correct authorities for the new user. This works fine for one server session and I can log in with the new user. However, on server restart, the user needs to be re-added. I want to prevent this.
I have a feeling that I need to do something more elaborate like configuring a persistent datasource. If that is the case, could you please point me to some resource that uses java config to do this. I am just starting on spring and this may be a basic question and of everything that I read, I am not sure what to follow.
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.
and appropriate DB properties inside application.properties e.g.
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 tocreate-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)
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