当我在Spring Data JPA中使用Repository接口时会发生什么?

时间:2016-11-13 21:58:31

标签: java spring spring-data spring-data-jpa

我有简单的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);
        // ...

    }
}

0 个答案:

没有答案