I have a simple entity class:
@Entity(name = "User")
@Table(name = "users")
@Data
@NoArgsConstructor
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private Integer age;
private String email;
}
A repository:
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
}
A service:
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Iterable<User> findAllUsers() {
return userRepository.findAll();
}
public <U extends User> void saveUser(U user) {
userRepository.save(user);
}
}
A controller:
@RestController
@RequestMapping("api/v1/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public Iterable<User> getAllUsers() {
return userService.findAllUsers();
}
@PostMapping
public void addUser(@RequestBody User user) {
userService.saveUser(user);
}
}
And a yaml file:
spring:
datasource:
username: "root"
password: "123123"
url: "jdbc:mysql://localhost:3306/mydbtest"
driverClassName: "com.mysql.jdbc.Driver"
jpa:
hibernate.ddl-auto: update
generate-ddl: true
show-sql: true
I use MYSQL Workbench, where I have a database with one table called users. Sending a get request and trying to get all the objects from the table, I get an empty json. What should I do?
CodePudding user response:
Your code seems ok to me . I think its your IDE issue, you have to enable Lombok annotation processing in your IDE. You can follow this link to enable it.
CodePudding user response:
Could you add @AllArgsConstructor
annotation to your entity. I think it might solve your issue. Since currently you only have @NoArgsConstructor
and @RequiredArgsConstructor
which comes bundled with @Data
. And also you don't necessarily need the name paramenter in @Entity