头图

jpa operation database

Note: The database uses the local database, the following is the table building statement and initialization data:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` bigint(0) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `dpt_id` bigint(0) NULL DEFAULT NULL COMMENT '部门id',
  `name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名',
  `age` int(0) NULL DEFAULT NULL COMMENT '年龄',
  `email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邮箱',
  `head_img` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '头像',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 0 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户类' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 1, 'Jone', 18, 'test1@baomidou.com', 'e');
INSERT INTO `user` VALUES (2, 1, 'Jack', 20, 'test2@baomidou.com', 'd');
INSERT INTO `user` VALUES (3, 1, 'Tom', 28, 'test3@baomidou.com', 'c');
INSERT INTO `user` VALUES (4, 1, 'Sandy', 21, 'test4@baomidou.com', 'b');
INSERT INTO `user` VALUES (5, 1, 'Billie', 24, 'test5@baomidou.com', 'a');

SET FOREIGN_KEY_CHECKS = 1;

Configure the data source in idea: idea-->view-->tool windows-->database

Create a project and add the following dependencies

<!--springboot web依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--springboot 操作数据库使用jpa的依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql数据库连接驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok 一款神器,后面专题介绍-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

Add the following database configuration to application.yml under the created project

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?charset=UTF-8&serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

Build the project directory structure as follows

user code:

@Entity//标识这个是一个与数据库表对应的entity类
@Data//lombok神器的一个注解,后面专题介绍
@Table ( name ="user" )//这个类是与数据库的哪个表对应的
public class User implements Serializable {

   private static final long serialVersionUID =  829933141479418804L;

   /**
    * 主键ID
    */
   @Id//这个字段是数据库表的主键
       @Column(name = "id" )//这个属性对应表的哪个字段
   @GeneratedValue(strategy= GenerationType.IDENTITY)//主键采用数据库自增方式
   private Long id;

   /**
    * 部门id
    */
       @Column(name = "dpt_id" )
   private Long dptId;

   /**
    * 姓名
    */
       @Column(name = "name" )
   private String name;

   /**
    * 年龄
    */
       @Column(name = "age" )
   private Long age;

   /**
    * 邮箱
    */
       @Column(name = "email" )
   private String email;

   /**
    * 头像
    */
       @Column(name = "head_img" )
   private String headImg;

}

The strategy attribute of the @GeneratedValue

  1. -AUTO: The main key is controlled by the program and is the default option. This option is not set.
  2. -IDENTITY: The primary key is automatically generated by the database, that is, the database ID self-growth method is adopted. Oracle does not support this method.
  3. -SEQUENCE: Generate the primary key through the sequence of the database, specify the sequence name through the @SequenceGenerator annotation, mysql does not support this method.
  4. -TABLE: Generate the primary key through a specific database table. Using this strategy can make the application easier for database migration.

userJpa code:

@Repository//表示这个是一个操作数据库的Repository类

public interface UserJpa extends JpaRepository<User,Long> {
}

userController code:

@RestController
@RequestMapping("user")

public class UserController {

    @Resource
    private UserJpa userJpa;

    @GetMapping("findAll")//查找所有数据
    public List<User> findAll(){
        return this.userJpa.findAll();
    }

    @GetMapping("get")//按主键查找数据
    public User get(@RequestParam("id")Long id){
        return this.userJpa.findById(id).get();
    }
}

Start the project, and then test with postman: query all:

Query the data of the specified id

No sql was written during the whole process, so the data was queried like this. Well, that's it for this section. The next section introduces save, delete, update, custom sql

More original reading: https://javawu.com


大盛玩java
24 声望5 粉丝