1、新建spring boot项目
2、引入jap和数据库驱动依赖
<!--添加springdata-jpa依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--添加MySQL驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
3、简单yml配置
spring:
jpa:
show-sql: true
datasource: #数据库相关
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&serverTimezone=GMT
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
4、实体类
package com.llg.entity;
import javax.persistence.*;
@Table(name = "users")
@Entity
public class Users {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@Column(name = "username")
private String username;
@Column(name = "password")
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;
}
}
5、dao层
package com.llg.dao;
import com.llg.entity.Users;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface UserDao extends JpaRepository<Users, Integer>, JpaSpecificationExecutor<Users> {
@Query(value = "select * from users", nativeQuery = true)
List<Users> listUser();
}
6、service层
package com.llg.service;
import com.llg.dao.UserDao;
import com.llg.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
UserDao userDao;
public List<Users> listUser(){
return userDao.listUser();
}
}
7、controller层
package com.llg.controller;
import com.llg.entity.Users;
import com.llg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("listUser")
public List<Users> listUser(){
return userService.listUser();
}
}
8、测试,访问:localhost:8080/listUser