I have simple Spring Boot application.
And when I use Spring Data JPA I'm confused. Because I don't understand all this magic.
Ok, magic comes with Spring in runtime. But what exactly is happening there?
We just create proxy object for UserRepository interface and generate code for User findByLoginName(String loginName)
method?
Can you please describe with details what happens under the hood in Spring Data JPA?
Entity object User.java
:
import javax.persistence.*;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private Long id;
@Column(nullable = false)
private String loginName;
@Column(nullable = false)
private String pwd;
@Column(nullable = false)
private Boolean enabled;
// getters and setters...
}
Repository interface UserRepository.java
:
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByLoginName(String loginName);
}
Usage our UserRepository
in UserController.java
:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class UserController {
@Autowired
private UserRepository userRepository;
@ResponseBody
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String get(@RequestParam("name") String name) {
final User user = userRepository.findByLoginName(id);
// ...
}
}