1. 首先,在 pom.xml 文件中添加 JPA 依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
  1. 定义实体类
@Entity
@Table(name = 'user')
public class User {

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

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

    @Column(name = 'age')
    private Integer age;

    // 省略 getter 和 setter 方法
}
  1. 定义 Repository 接口
public interface UserRepository extends JpaRepository<User, Long> {

    List<User> findByName(String name);

    List<User> findByAge(Integer age);
}
  1. 编写 Controller 类
@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping('/user')
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @GetMapping('/user/{name}')
    public List<User> getUserByName(@PathVariable String name) {
        return userRepository.findByName(name);
    }

    @GetMapping('/user/age/{age}')
    public List<User> getUserByAge(@PathVariable Integer age) {
        return userRepository.findByAge(age);
    }
}
  1. 在前端页面中通过发送 HTTP 请求获取数据并展示
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>User List</title>
    <script src='https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
</head>
<body>
    <h1>User List</h1>
    <table>
        <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
        </tr>
        </thead>
        <tbody id='userList'>
        </tbody>
    </table>
    <script>
        $(function () {
            $.get('/user', function (data) {
                for (var i = 0; i < data.length; i++) {
                    var user = data[i];
                    var tr = $('<tr></tr>');
                    tr.append('<td>' + user.id + '</td>');
                    tr.append('<td>' + user.name + '</td>');
                    tr.append('<td>' + user.age + '</td>');
                    $('#userList').append(tr);
                }
            });
        });
    </script>
</body>
</html>

运行程序,访问 http://localhost:8080/user,即可获取所有用户的信息。访问 http://localhost:8080/user/{name},可以根据用户名获取用户信息。访问 http://localhost:8080/user/age/{age},可以根据用户年龄获取用户信息。以上代码仅供参考,实际情况可能需要根据具体需求进行修改。

使用 JPA 接口调用数据库数据并显示在网页

原文地址: https://www.cveoy.top/t/topic/oXGu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录