SpringBoot + Maven + Hibernate ( 簡單實現CRUD功能 )


工具:idea、mariadb數據庫

 創建一個項目 ( student )

........(使用idea創建一個springboot項目,這里我就不多說了)

 

 Maven 中的依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- 父模塊 -->
    <!-- 包含了自動配置、日志....... -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.demo</groupId>
    <artifactId>student</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>student</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!-- springboot 自動配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- 測試框架 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

        <!-- jap 只是一個規范 -->
        <!-- SpringDataJpa 是 jap規范 再次抽象封裝,底層還是使用 Hibernate的JPA技術實現 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

        <!-- mariaDB 數據庫 -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>2.3.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <!-- maven 插件 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
View Code

創建 entity、dao、service、(service包還有一個impl包)、 controller 包

 

數據庫

create table student(
    stu_id int primary key auto_increment,
    stu_number varchar(20) not null,
    stu_name varchar(10) not null,
    stu_age int not null,
    stu_sex varchar(2) not null
)default charset=utf8;

insert into student(stu_number,stu_name,stu_age,stu_sex) values
('A1001','歐可樂',19,''),
('B2001','啦啦啦',18,''),
('C3001','舞舞舞',18,''),
('D4001','飛飛飛',20,''),
('E5001','噠噠噠',19,'');
View Code

配置application.yml 文件

yml格式

spring:
  datasource:
    driver-class-name: org.mariadb.jdbc.Driver
    url: jdbc:mariadb://localhost:3306/test
    username: oukele
    password: oukele
  jpa:
    hibernate:
      # 每次運行程序更新數據
      ddl-auto: none
    # 是否顯示sql語句
    show-sql: true
    # 格式化sql語句
    properties:
      hibernate:
        format_sql: true
    # 設置數據庫方言
    database-platform: org.hibernate.dialect.MySQL5Dialect

#mysql數據庫
#spring:
#  datasource:
#    driver-class-name: com.mysql.cj.jdbc.Driver
#    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=true
#    username: 
#    password: 
#    jpa:
#      hibernate:
#        ddl-auto: none
#      show-sql: true
#      properties:
#        hibernate:
#          format_sql: true
#      database-platform: org.hibernate.dialect.MySQL5Dialect
View Code

properties格式

spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/test
spring.datasource.username=oukele
spring.datasource.password=oukele

spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
View Code

在entity包中新建一個Studen類

package com.demo.student.entity;

import javax.persistence.*;

/**
 * 學生實體類
 *
 * @author OUKELE
 * @create 2019-04-13 16:18
 */

//實體類的標志
@Entity
//對應的數據庫表名
@Table(name = "student")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增長主鍵
    private int stuId;

    // 數據庫字段名 不區分大小寫
    // 數據庫名列為stu_number Hibernate 會按照駝峰命名規范幫我們轉換成 stuNumber
    //@Column(name = "stu_number")
    private String stuNumber;
    
    private String stuName;
    private int stuAge;
    private String stuSex;

    public int getStuId() {
        return stuId;
    }

    public void setStuId(int stuId) {
        this.stuId = stuId;
    }

    public String getStuNumber() {
        return stuNumber;
    }

    public void setStuNumber(String stuNumber) {
        this.stuNumber = stuNumber;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public int getStuAge() {
        return stuAge;
    }

    public void setStuAge(int stuAge) {
        this.stuAge = stuAge;
    }

    public String getStuSex() {
        return stuSex;
    }

    public void setStuSex(String stuSex) {
        this.stuSex = stuSex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "stuId=" + stuId +
                ", stuNumber='" + stuNumber + '\'' +
                ", stuName='" + stuName + '\'' +
                ", stuAge=" + stuAge +
                ", stuSex='" + stuSex + '\'' +
                '}';
    }
}
View Code

在dao包中新建一個StudentDao接口,並繼承 CrudRepository 接口

CrudRepository 着簡單crud方法,默認滴

package com.demo.student.dao;

import com.demo.student.entity.Student;
import org.springframework.data.repository.CrudRepository;

public interface StudentDao extends CrudRepository<Student,Integer> {

}
View Code

新建一個dao包,用於測試studentDao接口

package com.demo.student.dao;

import com.demo.student.entity.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * 測試接口
 *
 * @author OUKELE
 * @create 2019-04-13 16:43
 */

@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentDaoTest {

    @Autowired
    private StudentDao studentDao;

    // 測試 查詢 student 表中所有的數據
    @Test
    public void getList(){
        List<Student> list = (List<Student>) studentDao.findAll();
        System.out.println(list);
    }

    // 測試 向 student 表 新增一條記錄
    //.........

}

 接口測試

 

 在service包新建一個我們的接口(StudentService)

package com.demo.student.service;

import com.demo.student.entity.Student;

import java.util.List;

public interface StudentService {

    List<Student> listAll();

    int save(Student student);

    int delete(int stuId);

    int update(Student student);

}
View Code

在service包新建一個impl包 ,然后在impl包新建一個StudentServiceImpl類,並實現StudentSerice接口

package com.demo.student.service.Impl;

import com.demo.student.dao.StudentDao;
import com.demo.student.entity.Student;
import com.demo.student.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author OUKELE
 * @create 2019-04-13 18:24
 */

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    @Override
    public List<Student> listAll() {
        return (List<Student>) studentDao.findAll();
    }

    @Override
    public int save(Student student) {
        return studentDao.save(student)!= null ? 1:0;
    }

    @Override
    public int delete(int stuId) {
        int i = 0;
        try {
            studentDao.deleteById(stuId);
            i = 1;
        } catch (Exception e) {
            e.printStackTrace();
            i = 0;
        }
        return i;
    }

    @Override
    public int update(Student student) {
        return studentDao.save(student) !=null ? 1:0;
    }
}
View Code

在controller包新建一個StudentController類

package com.demo.student.controller;

import com.demo.student.entity.Student;
import com.demo.student.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author OUKELE
 * @create 2019-04-14 17:24
 */

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/list")
    public Object list(){
        List<Student> list = studentService.listAll();
        if( list == null ) return "{\"msg\":\"無數據\"}";
        return studentService.listAll();
    }

    @PostMapping("/insert")
    public String insert(Student student){
        int save = studentService.save(student);
        if (save>0)return "{\"msg\":\"新增成功\"}";
        return "{\"msg\":\"新增失敗\"}";
    }

    @PostMapping("/update")
    public String update(Student student){
        int save = studentService.save(student);
        if (save>0)return "{\"msg\":\"更新成功\"}";
        return "{\"msg\":\"更新失敗\"}";
    }

    @GetMapping("/delete")
    public String delete(@RequestParam int stuId){
        int delete = studentService.delete(stuId);
        if(delete >0)return "{\"msg\":\"刪除成功\"}";
        return "{\"msg\":\"刪除失敗\"}";
    }



}
View Code

 啟動項目,進行訪問

 

演示項目源碼:https://github.com/oukele/SpringBoot-Hibernate-demo1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM