Java技术分享:SpringBoot+mysql+...

本文涉及的产品
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
简介: 放个效果图:

放个效果图:

准备项目

首先在MySql控制台输入一下sql语句创建student 数据库和student。

create databse student;
use student;
CREATE TABLE `student` (
  `stu_id` bigint(20) NOT NULL,
  `stu_name` varchar(45) DEFAULT NULL,
  `stu_sex` varchar(6) DEFAULT NULL,
  `date` varchar(45) DEFAULT NULL,
  `room` int(2) DEFAULT NULL,
  `acadimy` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`stu_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
123456789101112

SpringBoot

修改项目名称,点击next

这里直接点next

第一次打开会很慢
打开后删除用不到的文件

连接MySql

修改 application.properties 为 application.yml

插入一下代码
要修改的内容: url: jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC&&characterEncoding=utf-8中的student改为自己的数据库名称

spring:
  #配置 数据库
  datasource:
    username: root #用户名
    password: akbar #密码
    #下一行中student 改为 自己建的database 
    url: jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC&&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
#    配置JSP 路径
  mvc:
    view:
      prefix: /     
      suffix: .jsp
#mybatis-plus 打印日志 不需要手写sql 可查看把我们完成的sql 
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 设置端口号
server:
  port: 8001
12345678910111213141516171819202122

pom.xml 依赖包

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--        MYsql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
<!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>
        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- servlet依赖的jar包start -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <!-- servlet依赖的jar包start -->
        <!-- jsp依赖jar包start -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <!-- jsp依赖jar包end -->
        <!--jstl标签依赖的jar包start -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465

IDEA 链接数据库

IDEA 链接本地MySql数据库 (可以确定Mysql能正常访问 ,方便我们调试)
1.点击屏幕右侧Database
2.点击如下如的加号
3.DataSource
4.选择Mysql


**如上图所示表示成功连接,如果报错,检查用户名,密码,数据库名称 **

常见问题:时区(time zone)相关的报错Mysql控制台写下面的代码 重新Test Connection 。

set global time_zone='+8:00';
1

连接成功可以看到刚才见的数据库

为了方便我们测试点击加号“+”增加两条记录

增加完成后点击如下图DB的小图标(如果没看到鼠标移到大概位置会显示别出来)

代码生成器(不用我们自己写实体类,controller ,mapper,service等)

在下图目录下测试类新建一个类GenerateCode

代码如下:

需要修改的地方:
1.这里修改成你自己的

pg.setParent("com.example.xxxx");
1

2.改称自己的昵称

gc.setAuthor("艾科");  
1

3.把下边的student 改为自己建的数据库名称

dsc.setUrl("jdbc:mysql://localhost:3306/studentuseSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");`
1

4.// 版本8.0以下去掉中间的cj

dsc.setDriverName("com.mysql.cj.jdbc.Driver"); //8.0
dsc.setDriverName("com.mysql.jdbc.Driver"); //8.0以下
12
  1. 数据库用户名和密码
dsc.setUsername("root");
 dsc.setPassword("root"); 
12

6.最后一个也是最重要的:这里是自己的数据不哭表

strategy.setInclude("student");
1

代码如下:

public class GenerateCode {
    public static void main(String[] args) {
        AutoGenerator ag=new AutoGenerator();
//         全局配置
        GlobalConfig gc=new GlobalConfig();
        String projectPath=System.getProperty("user.dir"); //获取项目根目录
        gc.setOutputDir(projectPath+"/src/main/java");  //设置输出目录
        gc.setAuthor("艾科");  //代码注解
        gc.setOpen(false); 
        gc.setFileOverride(false);  //是否覆盖(选否)不然会覆盖掉写过的代码
        gc.setServiceName("%sService"); 
        gc.setIdType(IdType.ID_WORKER);  // 可以根据需求改成IdType.AUTO 或者其他
        gc.setDateType(DateType.ONLY_DATE);  //Date 类型 只使用 java.util.date 代替
        ag.setGlobalConfig(gc);
//         设置数据源
        DataSourceConfig dsc=new DataSourceConfig();  //不要忘了修改数据库名称
        dsc.setUrl("jdbc:mysql://localhost:3306/student?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");//8.0用com.mysql.cj.jdbc.Driver 5.7用com.mysql.jdbc.Driver
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setDbType(DbType.MYSQL); //数据库类型
        ag.setDataSource(dsc);
//      包的配置
        PackageConfig pg=new PackageConfig();
//         pg.setModuleName("")
        pg.setParent("com.example.xxxx");  //把xxx 改成你自己的
        pg.setEntity("entity"); //实体类创建目录
        pg.setMapper("mapper");//mapper
        pg.setController("controller");//controoler
        ag.setPackageInfo(pg);
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel); //代码风格驼峰结构
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(false);
        strategy.setRestControllerStyle(true);
        strategy.setInclude("student");     // table 名称 ,根据table 名称生成 实体类,controller,service, mmapper  
     //   strategy.setInclude("student,user,class");     // 多个表用都逗号分开
        strategy.setControllerMappingHyphenStyle(true);
        ag.setStrategy(strategy);
        ag.execute();
    }
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748

改完了执行该类

MyBatis Plus

把下图目录中的xxxxApplication 加上 @MapperScan(“com.xxxx.xx.mapper”) mapper 包名r如下图所示(改成你自己的mapper 的包名)


**如果怕敲错可以复制StudentMpaper 中的packege **

@MapperScan("com.example.student.mapper")
@SpringBootApplication
public class StudentApplication {
    public static void main(String[] args) {
        SpringApplication.run(StudentApplication.class, args);
    }
}
123456789

MyBatis Plus 简单查询 (这个可以留到最后写作业的时候学 PS:肯定会用到)

@Autowired
      StudentMapper studentMapper;
    //        Mybatis plus 查询 student 表中的数据 返回List 类型
//    相当于:    SELECT stu_id,stu_name,stu_sex,date,room,acadimy FROM student
        List<Student> list = studentMapper.selectList(null);
        list.forEach(System.out::println);
//        通过id 查询  相当于:SELECT stu_id,stu_name,stu_sex,date,room,acadimy FROM student WHERE stu_id=1
        Student student1 = studentMapper.selectById(1);
//        条件查询 查询单个 相当于:SELECT stu_id,stu_name,stu_sex,date,room,acadimy FROM student WHERE stu_name = ? AND stu_sex = ?
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_name", "小明");
        wrapper.eq("stu_sex", "男");
        Student student2 = studentMapper.selectOne(wrapper);
        //        条件查询 查询列表  相当于:SELECT stu_id,stu_name,stu_sex,date,room,acadimy FROM student WHERE stu_id > 1
        QueryWrapper<Student> wrapper1 = new QueryWrapper<>();
        wrapper1.gt("stu_id", 1);
        Student student3 = studentMapper.selectOne(wrapper1);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String date=simpleDateFormat.format(System.currentTimeMillis());
//        insert 相当于 :
//        INSERT INTO student ( stu_id, stu_name, stu_sex, date, room, acadimy ) VALUES ( ?, ?, ?, ?, ?, ? ) 
//==> Parameters: 1280830334286217217(Long), aike(String), 男(String), 2020-07-08(String), 226(Integer), 计算机(String)
        Student student=new Student();
        student.setStuName("aike");
        student.setStuSex("男");
        student.setDate(date);
        student.setRoom(226);
        student.setAcadimy("计算机");
        studentMapper.insert(student);
1234567891011121314151617181920212223242526272829303132333435363738

更多复杂查询查询官网-----> MyBatis-Plus 官网

访问JSP页面

之前在pom.xml 中导入了相关的依赖包了

在mian 目录下创建 webapp 文件夹


在webapp 目录下创建 student.jsp文件

student.jsp文件内容如下 把下面的文件放到 student.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
         pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>学生信息</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript">
        inserrtStudent= function()  {
            console.log("新增学生")
            alert("新增学生")
        }
        inserrtRoom = function () {
            alert("新增宿舍")
        }
        updateRoom =function ( ) {
            alert("修改宿舍")
        }
        updateRecord  =function (stu) {
            alert("查询记录:"${stu.stu_name})
        }
    </script>
</head>
<body>
<div class="row">
    <div class="col-md-6">
        <table class="table table-striped">
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>性别</th>
                <th>学院</th>
                <th>入学时间</th>
                <th>宿舍号</th>
                <td><button class="btn btn-success" onclick="return inserrtStudent()" >新增学生</button></td>
                <td><button class="btn btn-success" onclick=" return inserrtRoom()">新增宿舍</button></td>
            </tr>
            <c:if test="${not empty students}">
                <c:forEach items="${students}" var="stu">
                    <tr>
                        <td>${stu.stuId}</td>
                        <td>${stu.stuName}</td>
                        <td>${stu.stuSex}</td>
                        <td>${stu.acadimy}</td>
                        <td>${stu.date}</td>
                        <td>${stu.room}</td>
                        <td><button class="btn btn-default" onclick="return updateRoom(${stu})">修改宿舍</button></td>
                        <td><button class="btn btn-default" onclick="return updateRecord()">查询记录</button></td>
                    </tr>
                </c:forEach>
            </c:if>
        </table>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</body>
</html>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970

StudentControoler 代码如下

注意:StudentController注解是 @Controller 而不是 RestController 。

/**
 *
 * @author 艾科
 * @since 2020-07-08
 */
@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    StudentMapper studentMapper;
    @RequestMapping(value = "findall")
    public String findAll(Model model) {
//        Mybatis plus 查询 student 表中的数据 返回List 类型
//    相当于:    SELECT stu_id,stu_name,stu_sex,date,room,acadimy FROM student
        List<Student> list = studentMapper.selectList(null);
        model.addAttribute("students", list);
        return "student";
    }
}
12345678910111213141516171819202122

运行结果(运行按钮在右上角):localhost:你的端口号/student/findall


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
4月前
|
SQL Java 关系型数据库
Java连接MySQL数据库环境设置指南
请注意,在实际部署时应该避免将敏感信息(如用户名和密码)硬编码在源码文件里面;应该使用配置文件或者环境变量等更为安全可靠地方式管理这些信息。此外,在处理大量数据时考虑使用PreparedStatement而不是Statement可以提高性能并防止SQL注入攻击;同时也要注意正确处理异常情况,并且确保所有打开过得资源都被正确关闭释放掉以防止内存泄漏等问题发生。
176 13
|
6月前
|
Java 数据库连接 API
Java 8 + 特性及 Spring Boot 与 Hibernate 等最新技术的实操内容详解
本内容涵盖Java 8+核心语法、Spring Boot与Hibernate实操,按考试考点分类整理,含技术详解与代码示例,助力掌握最新Java技术与应用。
189 2
|
7月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
282 1
|
6月前
|
人工智能 Java 关系型数据库
Java的时间处理与Mysql的时间查询
本文总结了Java中时间与日历的常用操作,包括时间的转换、格式化、日期加减及比较,并介绍了MySQL中按天、周、月、季度和年进行时间范围查询的方法,适用于日常开发中的时间处理需求。
115 0
|
7月前
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
295 1
|
8月前
|
安全 Java API
Spring Boot 功能模块全解析:构建现代Java应用的技术图谱
Spring Boot不是一个单一的工具,而是一个由众多功能模块组成的生态系统。这些模块可以根据应用需求灵活组合,构建从简单的REST API到复杂的微服务系统,再到现代的AI驱动应用。
|
7月前
|
Java 调度 流计算
基于Java 17 + Spring Boot 3.2 + Flink 1.18的智慧实验室管理系统核心代码
这是一套基于Java 17、Spring Boot 3.2和Flink 1.18开发的智慧实验室管理系统核心代码。系统涵盖多协议设备接入(支持OPC UA、MQTT等12种工业协议)、实时异常检测(Flink流处理引擎实现设备状态监控)、强化学习调度(Q-Learning算法优化资源分配)、三维可视化(JavaFX与WebGL渲染实验室空间)、微服务架构(Spring Cloud构建分布式体系)及数据湖建设(Spark构建实验室数据仓库)。实际应用中,该系统显著提升了设备调度效率(响应时间从46分钟降至9秒)、设备利用率(从41%提升至89%),并大幅减少实验准备时间和维护成本。
381 0

推荐镜像

更多