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

posted @ 2019-04-13 15:09  追梦滴小蜗牛  阅读(2824)  评论(0编辑  收藏  举报