Yagami Light
Yagami Light

Reputation: 1796

Create admin account by default in Spring boot

I have a user entity:

User.java

@Entity
public class user {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotNull
@NotBlank
private String firstname;
...

When I am deploying the application the first time it will create this table in my database.

My question: is there any way to create an admin user with firstname together with the table user when it gets created?

Upvotes: 5

Views: 9524

Answers (2)

anothernode
anothernode

Reputation: 5397

This answer actually shows a better approach and should be the accepted one.


You can put something like this in src/main/resources/data.sql:

INSERT INTO users (firstname, password, enabled)
SELECT 'admin', 'secret', TRUE
WHERE NOT EXISTS (SELECT * FROM users WHERE firstname='admin');

Assuming you are using PostgreSQL for the database backend.

As I don't know the database schema you are using, you'll have to modify this query to match your schema, but it should give you the basic idea.

I think you don't even need to add any configuration for this to work as Spring will pick it up automatically and use it for database initialization if it's in the right directory.

According to another answer to a similar question, in Spring Boot 2.x you'll have to add the following piece of configuration for this to work:

spring.datasource.initialization-mode=always

Upvotes: 2

Issam EL-GUERCH
Issam EL-GUERCH

Reputation: 414

i prefer always to avoid sql script so i use CommandLineRunner interface. this is an example using spring data, its not a working code :

@Component    
public class CommandLineAppStartupRunner implements CommandLineRunner {
    @Autowired
    UserRepository userRepository;

    @Override
    public void run(String...args) throws Exception {
        User admin = new user(firstName);
        userRepository.save(admin);
    }
}

before the app starts this class will be executed.

Upvotes: 8

Related Questions