欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot jpa 操作mysql

程序员文章站 2022-04-20 21:11:43
...

1. 创建springboot项目

2. 编写application.yml配置文件

server:
  port: 8080
  servlet:
    context-path: /

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
    username: root
    password: root
    # type: com.alibaba.druid.pool.DruidDataSource  # 链接池 druid

  jpa:
    database: mysql
    show-sql: true # 显示sql
    hibernate:
      ddl-auto: update # jpa的正向工程

3. 编写实体类

  • pojo.User.java
package com.adley.studyspringdatajpa.pojo;

import javax.persistence.*;


@Entity
@Table(name="t_users")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

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

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

    @Column(name = "address")
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

4. 编写dao接口

  • dao.UserRepository.java
package com.adley.studyspringdatajpa.dao;

import com.adley.studyspringdatajpa.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Integer> {
}

5. 编写service业务逻辑层

  • service.UserService.java
package com.adley.studyspringdatajpa.service;

import com.adley.studyspringdatajpa.dao.UserRepository;
import com.adley.studyspringdatajpa.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 保存一条用户信息
     */
    public User saveUser(User user) {
        return userRepository.save(user);
    }

    /**
     * 根据id删除一个用户信息
     */
    public void deleteUser(Integer id) {
        userRepository.deleteById(id);
    }

    /**
     * 更新用户
     */
    public User updateUser(User user) {
        return userRepository.saveAndFlush(user);
    }

    /**
     * 查询一条用户信息
     */
    public User findUserById(Integer id) {
        Optional<User> optional = userRepository.findById(id);
        return optional.orElseGet(User::new);
    }

    /**
     * 查询多条用户list 分页
     */
    public Map<String, Object> findUserAll(Integer pageNum, Integer pageSize) {
        List<User> content = userRepository.findAll(PageRequest.of(pageNum - 1, pageSize)).getContent();
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("content", content);
        return map;
    }

}

6. 编写单元测试TestMysql.java

package com.adley.studyspringdatajpa;

import com.adley.studyspringdatajpa.pojo.User;
import com.adley.studyspringdatajpa.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Map;

@SpringBootTest
public class TestMysql {

    @Autowired
    private UserService userService;

    /**
     * 添加一个用户
     */
    @Test
    void testSaveUser() {
        User user = new User();
        user.setName("王东东");
        user.setAge(21);
        user.setAddress("北京");

        /**
         * 返回保存的user信息
         */
        User save_user = userService.saveUser(user);
        System.out.println(save_user);
    }

    /**
     * 查找一个用户
     */
    @Test
    void testFindUser() {
        Integer id = 2;
        User user = userService.findUserById(id);
        System.out.println(user);
    }

    /**
     * 更新用户,只是更新部分字段
     */
    @Test
    void testUpdateUser() {
        Integer id = 3;
        User user = userService.findUserById(id);

        user.setAge(28);
        user.setName("王小龙");

        User user1 = userService.updateUser(user);
        System.out.println(user1);
    }

    /**
     * 查询用户列表
     */
    @Test
    void testFindUsers() {
        Map<String, Object> data = userService.findUserAll(1, 15);
        System.out.println(data);
    }

    /**
     * 删除一个用户
     */
    @Test
    void testDelteUserById() {
        Integer id = 2;
        userService.deleteUser(id);
    }
}

相关标签: java