Articles
Software
Gallery
Other works
Contacts

#Minimal Mysql example with Spring.html



        1. Create a new domain specific database and user
            {@begin=sql@
            CREATE DATABASE spring;
            CREATE USER 'spring'@'localhost' IDENTIFIED BY 'passwd';
            GRANT ALL PRIVILEGES ON spring.* TO 'spring'@'localhost';
            FLUSH PRIVILEGES;
            @end=sql@}
        2. Generate a Spring Boot application with the following dependencies:
            jpa
            mysql
        3. Configure Spring to connect to mysql
            {@begin=java@
            // File: src/main/resources/application.properties
            spring.datasource.url=jdbc:mysql://localhost:3306/spring
            spring.datasource.username=spring
            spring.datasource.password=passwd
            spring.jpa.hibernate.ddl-auto=update
            @end=java@}
        4. Create JTA classes to sync to the database
            {@begin=java@
            @Entity
            public
            class Sheep {
                @Id
                @GeneratedValue(strategy = GenerationType.IDENTITY)
                public Long id;
                public String name;

                Sheep(String name_) {
                    this.name = name_;
                }
            }
            // ---
            public
            interface SheepRepository
            extends JpaRepository {}
            @end=java@}
        5. Seed the database somehow
            {@begin=java@
            @Bean
            public
            CommandLineRunner cmdlr(SheepRepository repository) {
                return (args) -> {
                    repository.save(new Sheep("Ross"));
                    repository.save(new Sheep("Joe"));
                };
            }
            @end=java@}
        6. Validate
            {@begin=java@
            $ mysql -u root
            > use spring;
            > select * from sql_application$sheep;
            +----+------+
            | id | name |
            +----+------+
            |  1 | Ross |
            |  2 | Joe  |
            +----+------+
            @end=java@}