Spring Boot 学习之MySQL增删改查操作

Jackey Java 3,206 次浏览 , 没有评论
  1. pom.xml 添加依赖
    <!--mysql-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>

     

  2. application.properties 配置文件添加数据源连接
    #数据源的地址
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf8
    spring.datasource.username=root
    spring.datasource.password=123456
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.continue-on-error=false
    spring.datasource.test-while-idle=true
    #获取连接时候验证,会影响性能
    spring.datasource.test-on-borrow=false
    #在连接归还到连接池时是否测试该连接
    spring.datasource.test-on-return=false
    spring.datasource.validation-query=SELECT 1 FROM DUAL
    #空闲连接回收的时间间隔,与test-while-idle一起使用,设置5分钟
    spring.datasource.time-between-eviction-runs-millis=300000
    #连接池空闲连接的有效时间 ,设置30分钟
    spring.datasource.min-evictable-idle-time-millis=1800000
    spring.datasource.initial-size=5
    #指定连接池中最大的活跃连接数.
    spring.datasource.max-active=50
    #指定连接池等待连接返回的最大等待时间,毫秒单位.
    spring.datasource.max-wait=60000
    #指定必须保持连接的最小值
    spring.datasource.min-idle=5
    
    spring.jpa.database=MYSQL
    #是否打印显示sql语句到控制台
    spring.jpa.show-sql=true
    # 自动检查实体和数据库表是否一致,如果不一致则会进行更新数据库表
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

     

  3. 创建PersonDao.java
    package com.example.demo.dao;
    
    import com.example.demo.entity.Person;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface PersonDao extends JpaRepository<Person, Long> {
    
    }
    

     

  4. 创建Person.java
    package com.example.demo.entity;
    
    import javax.persistence.*;
    
    @Entity
    @Table(name = "person")
    public class Person {
        @Column(name = "id", nullable = false, length = 11)
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Id
        private Long id;
        @Column(name = "name", nullable = false, length = 20)
        private String name;
        @Column(name = "age", nullable = false, length = 3)
        private Integer age;
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long 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;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    

     

  5. 创建PersonService.java
    package com.example.demo.service;
    
    import com.example.demo.dao.PersonDao;
    import com.example.demo.entity.Person;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class PersonService {
        @Autowired
        private PersonDao personDao;
    
        /**
         * 添加/修改操作日志,当id不为空时,修改,id为空时自动新增一条记录
         * @param person
         * @return
         */
        public Person save(Person person) {
            return personDao.save(person);
        }
    
        /**
         * 根据ID获取一条记录
         * @param id
         * @return
         */
        public Person findOne(Long id) {
            return personDao.getOne(id);
        }
    
        /**
         * 获取所有记录
         * @return
         */
        public List<Person> findAll() {
            return personDao.findAll();
        }
    
        public void delete(Long id) {
            personDao.deleteById(id);
        }
    }
    

     

  6. 创建PersonController.java
    package com.example.demo.controller;
    
    import com.example.demo.entity.Person;
    import com.example.demo.service.PersonService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.List;
    
    @Controller
    @RequestMapping("/person")
    public class PersonController {
        @Autowired
        private PersonService personService;
    
        @RequestMapping("/add")
        @ResponseBody
        public String add() {
            Person person = new Person();
            person.setName("gopher");
            person.setAge(20);
            personService.save(person);
            return "true";
        }
    
        @RequestMapping("/update")
        @ResponseBody
        public String update(Long id) {
            Person person = new Person();
            person.setName("gopher_new");
            person.setAge(20);
            person.setId(id);
            personService.save(person);
            return "true";
        }
    
        @RequestMapping("get_one")
        @ResponseBody
        public String getOne(Long id) {
           Person person = personService.findOne(id);
           return person.toString();
        }
    
        @RequestMapping("get_all")
        @ResponseBody
        public String getAll() {
            List<Person> personList = personService.findAll();
            return personList.toString();
        }
    
        @RequestMapping("/delete")
        @ResponseBody
        public String delete(Long id) {
            personService.delete(id);
            return "true";
        }
    }
    

     

最后测试:

启动程序,自动创建person表,创建字段,参考Person.java的属性。

访问: http://127.0.0.1:8080/person/add,添加一条记录

访问:http://127.0.0.1:8080/person/update?id=1,更新id=1的记录

访问:http://127.0.0.1:8080/person/get_one?id=1,获取id=1的记录

访问:http://127.0.0.1:8080/person/get_all,获取所有记录(可以先访问http://127.0.0.1:8080/person/add,多插入几条记录)

访问:http://127.0.0.1:8080/person/delete?id=1,删除id=1的记录

测试完成。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go