mars_dev
mars_dev

Reputation: 639

Data initialization doesn't work in spring boot hibernate app

I am learning spring boot and trying my first sample app but have stuck on initialization of data. I am able to create tables but my data.sql file is not executing. Following is my Application file:

spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.initialization-mode=always

Category:

@Entity
@NoArgsConstructor
@Data
@Table(name="category")
public class Category {
    @Id
    private Long id;

    //Travel, Grocery,...
    private String name;

}

data.sql:

insert into category values (1,'Travel')
insert into category values (2,'Auto Loan')
insert into category  values (3,'Travel')

Controller:

    package com.example.codeengine.expense.controller;

import java.util.Collection;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.codeengine.expense.model.Category;
import com.example.codeengine.expense.repository.CategoryRepository;


@RestController
@RequestMapping("/api")
public class CategoryController {
    private CategoryRepository categoryRepository;

    public CategoryController(CategoryRepository categoryRepository) {
        super();
        this.categoryRepository = categoryRepository;
    }

    @GetMapping("/categories")
    Collection<Category> categories(){
        System.out.println(categoryRepository.findAll());
        return categoryRepository.findAll();
    }
}

Can someone please help me here?

Upvotes: 0

Views: 513

Answers (1)

Nitin Bisht
Nitin Bisht

Reputation: 5361

You need to add getter-setters to retrieve and set the data.

Either you can manually add getter-setters in Category class or you if you are using Lombok then you need to add annotations at class level as shown below:

@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Data
@Table(name="category")
public class Category {
    @Id
    private Long id;

    //Travel, Grocery,...
    private String name;

}

I have added annotation for getter-setter, constructors and toString method.

Upvotes: 1

Related Questions