SpringBoot整合使用spring-data-jpa(六)

SpringBoot整合使用spring-data-jpa

1. pom文件引入依赖



	4.0.0

	com.rp.springboot
	springboot-data-jpa
	0.0.1-SNAPSHOT
	jar

	springboot-data-jpa
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.5.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

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

		
			mysql
			mysql-connector-java
			runtime
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

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




2.配置文件

spring.datasource.url=jdbc:mysql://localhost:3306/jdbc
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3. 创建Dept实体类

@Entity(name="dept")
public class Dept {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "name")
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

4. 创建DeptDao

public interface DeptDao extends JpaRepository {

}

5. DeptController层

@RestController
public class DeptController {
    @Autowired
    private DeptDao deptDao;

    @RequestMapping("/findDept/{id}")
    public Object jpaIndex(@PathVariable("id") int id) {
        Optional deptOptional  = deptDao.findById(id);
        Dept deptResult = deptOptional .get();
        return deptResult == null ? "没有查询到数据" : deptResult;
    }
}

源码地址:https://github.com/ruiace/springboot-data-jpa.git

你可能感兴趣的:(SpringBoot)