引入包
<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配置数据库
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/zeno?useUnicode=true&characterEncoding=utf8 username: zeno password: zeno jpa: hibernate: ddl-auto: none show-sql: true
建立实体类
@Entity public class SysUser { @Id @GeneratedValue private Integer id; @Column(name="user_name") private String userName; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
建立接口类
public interface UserRepository extends JpaRepository<SysUser,Integer> { }
建立Controller层
@RestController @RequestMapping("/user") public class Weather { @Autowired UserRepository userRepository; @RequestMapping("/test") public String test(){ return "ok"; } @RequestMapping("/queryAll") public List queryAll(){ return userRepository.findAll(); } }
完成,测试
localhost:8080/user/queryAll
返回
[ { "id": 0, "userName": "aaa", "password": "aaa" }, { "id": 1, "userName": "bbb", "password": "bbb" } ]