我有简单的Spring Boot应用程序。
当我使用Spring Data JPA时,我很困惑。因为我不明白所有这些魔力。
好的,魔术在运行时附带Spring。但到底发生了什么?
我们只是为UserRepository接口创建代理对象并为User findByLoginName(String loginName)
方法生成代码?
您能否详细说明Spring Data JPA内幕的内容?
实体对象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...
}
存储库界面UserRepository.java
:
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByLoginName(String loginName);
}
在UserRepository
中使用我们的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);
// ...
}
}