【Demo系列】Spring Data JPA

项目准备

数据库脚本

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '主键id',
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
  `age` int(0) NULL DEFAULT NULL COMMENT '年龄',
  `gender` tinyint(1) NULL DEFAULT NULL COMMENT '性别',
  `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('a90bcd22f811a', '张三', 18, 0, '2022-11-24 16:14:34');
INSERT INTO `student` VALUES ('a90bcd22f811b', '李四', 23, 1, '2022-11-24 16:53:02');

SET FOREIGN_KEY_CHECKS = 1;

代码

1.创建maven项目
2.引入依赖

    <dependencies>
        <!-- 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>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3.配置文件

# 数据源配置
spring.datasource.url = jdbc:mysql://localhost:3306/jpa_study?serverTimezone=Asia/Shanghai
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
# jpa设置-显示SQL语句
spring.jpa.show-sql = true
# jpa设置-表内有数据时不会清空, 只会更新
spring.jpa.hibernate.ddl-auto=update

实体类:

import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

@Data
@Entity
@Table(name = "student")
public class Student {
    @Id
    @Column
    private String id;

    @Column
    private String name;

    @Column
    private int age;

    @Column
    private boolean gender;

    @Column
    private Date createTime;
}

Dao层:

import com.example.jpa.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentDao extends JpaRepository<Student, String>, JpaSpecificationExecutor<Student> {
}

Service层:

import com.example.jpa.dao.StudentDao;
import com.example.jpa.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentDao studentDao;

    public List<Student> findList(){
        return studentDao.findAll();
    }

}

Controller层:

import com.example.jpa.entity.Student;
import com.example.jpa.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @PostMapping("/findList")
    public List<Student> findList(){
        return studentService.findList();
    }
}

Post访问接口:

localhost:8090/student/findList
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Data JPA 是基于 Spring 框架的一种数据访问技术,它简化了 JPA 的编程模型,提供了一种更加方便、高效的数据库操作方式。使用 Spring Data JPA,我们可以通过定义接口的方式,轻松地实现对数据库的增、删、改、查等操作。 下面是一个简单的 Spring Data JPA 的示例代码: 首先,我们需要定义一个实体类,如下所示: ``` @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // 省略 getter 和 setter 方法 } ``` 接着,我们需要定义一个 Repository 接口,如下所示: ``` public interface UserRepository extends JpaRepository<User, Long> { } ``` 这里的 JpaRepository 是 Spring Data JPA 提供的一个接口,它包含了一些常用的数据库操作方法,例如:save、delete、findAll 等。我们只需要定义一个继承了 JpaRepository 的接口,并指定实体类和主键类型,就可以使用这些方法了。 最后,我们可以在代码中使用 UserRepository,例如: ``` @Service public class UserService { @Autowired private UserRepository userRepository; public void saveUser(User user) { userRepository.save(user); } public List<User> findAllUsers() { return userRepository.findAll(); } } ``` 在这个示例代码中,我们使用了 UserRepository 中的 save 和 findAll 方法,分别实现了保存用户和查询所有用户的功能。 希望这个示例代码能够帮助你理解 Spring Data JPA 的使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值