SpringBoot+MybatisPlus+Mysql+JSP

放個效果圖:

在這裏插入圖片描述

準備項目

首先在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;

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

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>

IDEA 鏈接數據庫

IDEA 鏈接本地MySql數據庫 (可以確定Mysql能正常訪問 ,方便我們調試)
1.點擊屏幕右側Database
2.點擊如下如的加號
3.DataSource
4.選擇Mysql
在這裏插入圖片描述




在這裏插入圖片描述
**如上圖所示表示成功連接,如果報錯,檢查用戶名,密碼,數據庫名稱 **

常見問題:時區(time zone)相關的報錯Mysql控制檯寫下面的代碼 重新Test Connection 。

set global time_zone='+8:00';

連接成功可以看到剛纔見的數據庫
在這裏插入圖片描述

爲了方便我們測試點擊加號“+”增加兩條記錄

增加完成後點擊如下圖DB的小圖標(如果沒看到鼠標移到大概位置會顯示別出來)

在這裏插入圖片描述

代碼生成器(不用我們自己寫實體類,controller ,mapper,service等)

在下圖目錄下測試類新建一個類GenerateCode

在這裏插入圖片描述

代碼如下:

需要修改的地方:
1.這裏修改成你自己的

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

2.改稱自己的暱稱

  gc.setAuthor("艾科");  

3.把下邊的student 改爲自己建的數據庫名稱

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

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

dsc.setDriverName("com.mysql.cj.jdbc.Driver"); //8.0
dsc.setDriverName("com.mysql.jdbc.Driver"); //8.0以下
  1. 數據庫用戶名和密碼
 dsc.setUsername("root");
 dsc.setPassword("root"); 

6.最後一個也是最重要的:這裏是自己的數據不哭表

strategy.setInclude("student");

代碼如下:

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();
    }

改完了執行該類

在這裏插入圖片描述

在這裏插入圖片描述

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);

    }
}

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);
        

更多複雜查詢查詢官網-----> 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/[email protected]/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/[email protected]/dist/jquery.min.js"></script>
<!-- 加載 Bootstrap 的所有 JavaScript 插件。你也可以根據需要只加載單個插件。 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
</body>
</html>

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";
    }

}

運行結果(運行按鈕在右上角):localhost:你的端口號/student/findall

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章