2019-02-25

Spring Data JPA专注于使用JPA在关系数据库中存储数据。其最引人注目的功能是能够在运行时从存储库接口自动创建存储库实现
被注解@Entity,表明它是一个JPA实体
@GeneratedValue表示应自动生成ID
@Id,使JPA将其识别为对象的ID
Spring Data JPA如此强大的原因:您不必编写存储库接口的实现。Spring Data JPA在您运行应用程序时动态创建实现。

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity // 这告诉Hibernate从这个类中创建一个表
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
    private String email;
import org.springframework.data.repository.CrudRepository;
import hello.User;
// 这将由Spring自动实现为名为userRepository的Bean
// CRUD refers Create, Read, Update, Delete
public interface UserRepository extends CrudRepository {
}
package com.example.one;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;

@Controller  // 这意味着此类是一个Controller
@RequestMapping(path = "/demo") //这意味着URL以/demo开头(在应用程序路径之后)
public class UserController {

    @Autowired  // 这意味着获取名为userRepository的bean,它由Spring自动生成,我们将使用它来处理数据
    private UserRepository userRepository;

    @GetMapping(path="/add") // Map ONLY GET Requests
    public @ResponseBody String addNewUser(@RequestParam String name, @RequestParam String email){
        // @ResponseBody 表示返回的String是响应,而不是视图名称
        // @RequestParam 表示它是来自GET或POST请求的参数
        User user = new User();
        user.setName(name);
        user.setEmail(email);
        System.out.println(user.toString());

        userRepository.save(user);
        return "Saved";
    }

    @GetMapping(path = "/all")
    public @ResponseBody Iterable getAllUsers(){
        // This returns a JSON or XML with the users
        return userRepository.findAll();

    }

}


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.3.RELEASE
         
    
   
    

        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        

        
        
            mysql
            mysql-connector-java
        


        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



"resources/application.properties"
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/spring_data
spring.datasource.username=root
spring.datasource.password=12345678
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

你可能感兴趣的:(2019-02-25)