首先要有一个spring boot项目
请看这篇 https://blog.csdn.net/a184838158/article/details/82593245
我们常说的JPA其实是Spring Data下的Spring Data Jpa子项目,Spring Data Jpa有多种实现,这里我用Hibernate做实现。
首先我们需要在pom.xml增加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
其次在application.yml中添加数据库连接等信息
server:
port: 10001
spring:
application:
name: test
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username: root
password: root
jpa:
database: MYSQL
show-sql: true
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
ddl-auto: update
编写实体
package com.fewstrong.Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity(name = "db_user")
public class User {
@Id
@Column
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(length = 64)
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Spring Data Jpa在在DAO层并不需要实现只需要编写一个接口,并使接口集成Repository接口,但是Spring Data Jpa提过了多个接口可继承,比如 CrudRepository、PagingAndSortingRepository、JpaRepository。其中 CrudRepository提供了CRUD的方法,PagingAndSortingRepository提供了分页和排序查询的方法,JpaRepository提供了一些常用的,更多的基础方法。
package com.fewstrong.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import com.fewstrong.Entity.User;
public interface UserRepository extends JpaRepository<User, Long>{
}
完成Service Controller的代码
package com.fewstrong.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.fewstrong.Entity.User;
import com.fewstrong.service.UserService;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value = "/all", method = { RequestMethod.GET })
public List<User> all() {
return userService.findAll();
}
}
package com.fewstrong.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fewstrong.Entity.User;
import com.fewstrong.jpa.UserRepository;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
public List<User> findAll() {
return userRepository.findAll();
}
}
启动项目,会自动创建表,填充一些数据
访问 http://localhost:10001/user/all