SSM框架--笔记
目录一一,Maven–1,创建maven工程二,Maven–1,概述–2,使用Maven–3,IDEA里配置Maven–4,创建Maven项目–5,添加jar包的依赖三,Spring Boot–1,概述–2,创建Spring Boot项目–3,给服务器添加资源–4,测试二一,SpringMVC–1,概述–2,原理–3,创建Module–4,入门案例二,SpringMVC的响应–1,概述–2,测试三
目录
一
一,Maven
–1,创建maven工程
1,File-New-Project-选中Maven-next-输入工程名和GroupId-Finish
2,打开pom.xml文件,添加jar包的位置,交给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>
<groupId>cn.tedu</groupId>
<artifactId>cgb2106maven01</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 添加mysql依赖,可以支持多个依赖,依赖以坐标体现 -->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--要和数据库版本匹配,
数据库是5.X的版本就添加5.X的依赖
数据库是8.X的版本就添加8.X的依赖
-->
<version>5.1.48</version>
</dependency>
</dependencies>
</project>
3,必须刷新,否则不下载
二,Maven
–1,概述
用来下载并且管理jar包的工具,用来构建项目的方式
仓库:
中央仓库/远程仓库: 本质上就是一个国外的网址
镜像仓库: 其实就是一个国内的网址,人家从中央仓库下载好了jar包,你可以直接用
本地仓库: 其实就是你自己定的一个文件夹的位置,用来存jar包的位置
依赖:
Maven会自动下载并管理相关的jar
坐标:
通过Maven下载很多的jar包,唯一的定位方式就是使用坐标.
GroupId: 通常指定组,值一般是指公司的域名
ArtifactId: 通常项目名称
Version: 是指版本号
命令:
maven提供了很多命令,常用的有clean , install
–2,使用Maven
1,解压Maven的压缩包
2,找到conf文件夹里的settings.xml文件,修改
3,修改两个地方:
本地仓库: 指定一个jar包的存放路径
镜像仓库: 指定一个从哪里下载jar包的网址
4,settings.xml文件代码如下
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!--
| This is the configuration file for Maven. It can be specified at two levels:
|
| 1. User Level. This settings.xml file provides configuration for a single user,
| and is normally provided in ${user.home}/.m2/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -s /path/to/user/settings.xml
|
| 2. Global Level. This settings.xml file provides configuration for all Maven
| users on a machine (assuming they're all using the same Maven
| installation). It's normally provided in
| ${maven.conf}/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -gs /path/to/global/settings.xml
|
| The sections in this sample file are intended to give you a running start at
| getting the most out of your Maven installation. Where appropriate, the default
| values (values used when the setting is not specified) are provided.
|
|-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ${user.home}/.m2/repository
-->
<localRepository>D:\Java\maven\resp</localRepository>
<!-- interactiveMode
| This will determine whether maven prompts you when it needs input. If set to false,
| maven will use a sensible default value, perhaps based on some other setting, for
| the parameter in question.
|
| Default: true
<interactiveMode>true</interactiveMode>
-->
<!-- offline
| Determines whether maven should attempt to connect to the network when executing a build.
| This will have an effect on artifact downloads, artifact deployment, and others.
|
| Default: false
<offline>false</offline>
-->
<!-- pluginGroups
| This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
| when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
| "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
|-->
<pluginGroups>
<!-- pluginGroup
| Specifies a further group identifier to use for plugin lookup.
<pluginGroup>com.your.plugins</pluginGroup>
-->
</pluginGroups>
<!-- proxies
| This is a list of proxies which can be used on this machine to connect to the network.
| Unless otherwise specified (by system property or command-line switch), the first proxy
| specification in this list marked as active will be used.
|-->
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxy.host.net</host>
<port>80</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
<!-- servers
| This is a list of authentication profiles, keyed by the server-id used within the system.
| Authentication profiles can be used whenever maven must make a connection to a remote server.
|-->
<servers>
<!-- server
| Specifies the authentication information to use when connecting to a particular server, identified by
| a unique name within the system (referred to by the 'id' attribute below).
|
| NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
| used together.
|
<server>
<id>deploymentRepo</id>
<username>repouser</username>
<password>repopwd</password>
</server>
-->
<!-- Another sample, using keys to authenticate.
<server>
<id>siteServer</id>
<privateKey>/path/to/private/key</privateKey>
<passphrase>optional; leave empty if not used.</passphrase>
</server>
-->
</servers>
<!-- mirrors
| This is a list of mirrors to be used in downloading artifacts from remote repositories.
|
| It works like this: a POM may declare a repository to use in resolving certain artifacts.
| However, this repository may have problems with heavy traffic at times, so people have mirrored
| it to several places.
|
| That repository definition will have a unique id, so we can create a mirror reference for that
| repository, to be used as an alternate download site. The mirror site will be the preferred
| server for that repository.
|-->
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository. The repository that
| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
<!-- 达内私服地址 -->
<!--<mirror>
<id>nexus</id>
<name>Tedu Maven</name>
<mirrorOf>*</mirrorOf>
<url>http://maven.tedu.cn/nexus/content/groups/public/</url>
</mirror>-->
<!--阿里私服地址-->
<mirror>
<id>ali</id>
<name>ali Maven</name>
<mirrorOf>*</mirrorOf>
<url>https://maven.aliyun.com/repository/public/</url>
</mirror>
<!--
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
-->
</mirrors>
<!-- profiles
| This is a list of profiles which can be activated in a variety of ways, and which can modify
| the build process. Profiles provided in the settings.xml are intended to provide local machine-
| specific paths and repository locations which allow the build to work in the local environment.
|
| For example, if you have an integration testing plugin - like cactus - that needs to know where
| your Tomcat instance is installed, you can provide a variable here such that the variable is
| dereferenced during the build process to configure the cactus plugin.
|
| As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
| section of this document (settings.xml) - will be discussed later. Another way essentially
| relies on the detection of a system property, either matching a particular value for the property,
| or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
| value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
| Finally, the list of active profiles can be specified directly from the command line.
|
| NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
| repositories, plugin repositories, and free-form properties to be used as configuration
| variables for plugins in the POM.
|
|-->
<profiles>
<!-- profile
| Specifies a set of introductions to the build process, to be activated using one or more of the
| mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
| or the command line, profiles have to have an ID that is unique.
|
| An encouraged best practice for profile identification is to use a consistent naming convention
| for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
| This will make it more intuitive to understand what the set of introduced profiles is attempting
| to accomplish, particularly when you only have a list of profile id's for debug.
|
| This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
<profile>
<id>jdk-1.4</id>
<activation>
<jdk>1.4</jdk>
</activation>
<repositories>
<repository>
<id>jdk14</id>
<name>Repository for JDK 1.4 builds</name>
<url>http://www.myhost.com/maven/jdk14</url>
<layout>default</layout>
<snapshotPolicy>always</snapshotPolicy>
</repository>
</repositories>
</profile>
-->
<!--
| Here is another profile, activated by the system property 'target-env' with a value of 'dev',
| which provides a specific path to the Tomcat instance. To use this, your plugin configuration
| might hypothetically look like:
|
| ...
| <plugin>
| <groupId>org.myco.myplugins</groupId>
| <artifactId>myplugin</artifactId>
|
| <configuration>
| <tomcatLocation>${tomcatPath}</tomcatLocation>
| </configuration>
| </plugin>
| ...
|
| NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
| anything, you could just leave off the <value/> inside the activation-property.
|
<profile>
<id>env-dev</id>
<activation>
<property>
<name>target-env</name>
<value>dev</value>
</property>
</activation>
<properties>
<tomcatPath>/path/to/tomcat/instance</tomcatPath>
</properties>
</profile>
-->
</profiles>
<!-- activeProfiles
| List of profiles that are active for all builds.
|
<activeProfiles>
<activeProfile>alwaysActiveProfile</activeProfile>
<activeProfile>anotherAlwaysActiveProfile</activeProfile>
</activeProfiles>
-->
</settings>
–3,IDEA里配置Maven
1,找到Maven设置的位置: File-Settings-选Builder,execution…-Build Tools-选择Maven
2,配置信息:
指定maven解压的位置
指定解压文件里的conf/settings.xml文件
指定本地仓库(IDEA自动完成)
3,以上操作,避免了jar包自动下载到默认位置C:\Users\Administrator.m2\repository占用系统空间的现象
–4,创建Maven项目
1,File-New-Project-选择Maven-next-输入工程名/GroupId-ok
2,通常创建好项目以后,第一步就是配置Maven,不然就把jar包都下载到了C盘.
3,IDEA里配置Maven(同上)
–5,添加jar包的依赖
1,修改pom.xml文件,使用dependencies标签,引入各种jar包.
2,指定jar包的坐标,Maven会自动下载.
3,检查本地仓库
三,Spring Boot
–1,概述
是一个Maven项目的延伸,也拥有pom.xml
优势: 简化了Maven的操作 , 嵌入了Tomcat
–2,创建Spring Boot项目
1, File-New-Project-选择Spring Initlize-next-输入Group名和Artifact名和选择java8
-next-选中Spring(Spring Web)-next-ok
2, 配置Maven
3,检查:
–3,给服务器添加资源
package cn.tedu.cgb2106boot01;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloBoot {
@RequestMapping("abc")
public String hello(){
return "hello spring boot";
}
}
–4,测试
1,开启服务器(运行main方法)
2,打开浏览器访问:
http://localhost:8080/abc
本机 端口号 要访问的资源
二
一,SpringMVC
–1,概述
框架: 是一个结构,框架提供了很多的类,由框架控制每个类调用的过程流程
SSM框架里,第一个S就是指SpringMVC,是一个框架.
是Spring框架的一个后续产品,遵循了MVC的设计模式,保证了程序间的松耦合.
SpringMVC主要作用:1,接受请求(解析请求参数) 2,做出响应
MVC的设计模式:
M是Model模型,用来封装数据
V是View视图,用来展示数据
C是Controller控制器,用来控制浏览器如何请求,做出数据响应
好处: 提高代码的复用性 , 松耦合
–2,原理
1,前端控制器DispatcherServlet:
当浏览器发送请求成功后,充当这调度者的角色,负责调度每个组件.
2,处理器映射器HandlerMapping:
根据请求的URL路径,找到能处理请求的类名和方法名
url: http://localhost:8080/hi , 找到Hello类里的hi()
3,处理器适配器HandlerAdapter:
正式开始处理业务,并把返回结果的结果交给DispatcherServlet
4,视图解析器ViewResolver:
找到正确的,能展示数据的视图,准备展示数据
5,视图渲染View:
展示数据
–3,创建Module
选中Project-右键-New-Module-选择Maven-next-输入Module的名字-next-finish
–4,入门案例
1, 导入jar包(被Spring Boot整合好了)
2, 准备一个启动类RunApp,用来启动服务器
package cn.tedu.mvc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//标记着这是springboot的启动类
@SpringBootApplication
public class RunApp {
public static void main(String[] args) {
SpringApplication.run(RunApp.class);//运行当前类
}
}
3, 准备一个类,补充方法
访问链接: http://localhost:8080/car/get
得到数据:123
package cn.tedu.mvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//完成springmvc的角色,接受请求和给出响应
//是MVC设计模式里的C控制器,接受请求和给出响应
@RestController
//标记着这个类是Controller是一个控制器+接受请求
@RequestMapping("car")//规定了url怎么访问这个类
public class HelloController {
//测试: http://localhost:8080/car/get
@RequestMapping("get")//规定了url怎么访问这个方法
public String show(){
return "123";
}
}
4, 测试
启动服务器,打开浏览器,访问正确的URL地址
二,SpringMVC的响应
–1,概述
SpringMVC可以接受请求,和做出响应数据,类型可以非常丰富
–2,测试
package cn.tedu.mvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//完成springmvc的角色,接受请求和给出响应
//是MVC设计模式里的C控制器,接受请求和给出响应
@RestController
//标记着这个类是Controller是一个控制器+接受请求+响应JSON串
@RequestMapping("car")//规定了url怎么访问这个类
public class HelloController {
//测试: http://localhost:8080/car/get
@RequestMapping("get")//规定了url怎么访问这个方法
public String show(){
return "123";
}
//测试: http://localhost:8080/car/abc
@RequestMapping("abc")
public int show2(){
return 100;
}
// SpringMVC框架除了能返回字符串,整数以外,还能返回对象信息
//测试: http://localhost:8080/car/get2
@RequestMapping("get2")
public Car get(){
Car c = new Car();
//给客户端准备数据
c.setId(718);
c.setName("保时捷");
c.setType("Cayman T");
c.setColor("红色");
c.setPrice(641000);
return c; //把对象信息 变成JSON字符串在浏览器展示
}
}
三,SpringMVC解析get请求的参数
–1,概述
请求方式8种,常见的就是get post
restful风格的数据,用来简化了get的写法
http://localhost:8080/car/insert?id=1&name=张三&age=18
http://localhost:8080/car/insert/1/张三/18
–2,测试
package cn.tedu.mvc;
import org.junit.Test;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//Springmvc解析get的请求参数
// http://localhost:8080/car/insert?id=1&name=张三&age=18
@RestController//接受请求做出响应
@RequestMapping("get")//规定了浏览器的访问方式
public class GetController{
//测试 http://localhost:8080/get/param4?id=100&name=BMW&type=X6&color=red&price=9.9
@RequestMapping("param4")
//public String param4(int id,String name,String type,String color,double price){
public Car param4(Car c){//直接用对象接受参数,框架会自动封装属性的值
return c;
}
//测试 http://localhost:8080/get/param3?id=100&name=张三&price=9.9
@RequestMapping("param3")
public String param3(int id,String name,double price){
return id+name+price;
}
//测试 http://localhost:8080/get/param2?id=100&name=张三
@RequestMapping("param2")
public void param2(int id,String name){
System.out.println(id);
System.out.println(name);
}
//测试 http://localhost:8080/get/param?id=100
@RequestMapping("param")
public String param(int id){
return "您的请求参数里id="+id ;
}
@Test //单元测试方法
public void get1(){
String url ="http://localhost:8080/car/insert?id=1&name=张三&age=18";
String[] a = url.split("\\?")[1].split("&");
for(String s : a){
String data = s.split("=")[1];
System.out.println(data);
}
}
}
三
一,SpringMVC解析restful的请求参数
–1,概述
简化了get方式参数的写法
普通的get传递的参数 http://localhost:8080/car/get?id=100&name=张三
restful传递的参数 http://localhost:8080/car/get2/100/张三
–2,测试
package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//位置:必须在所有资源之上的包里
@SpringBootApplication
public class RunApp {
public static void main(String[] args) {
SpringApplication.run(RunApp.class);
}
}
package cn.tedu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
//@Controller
//@ResponseBody
@RestController
@RequestMapping("car")
public class CarController {
//注意1:: 参数列表里的参数类型,最好使用引用类型,
//如果浏览器没有传值过来就用默认值,但使用基本类型会抛异常的
//解析普通的get传递的参数
//http://localhost:8080/car/get?id=100&name=张三
@RequestMapping("get")
// public String get(int id,String name){
public String get(Integer id,String name){
return id+name ;
}
//解析restful传递的参数:简化了get方式参数的写法
//http://localhost:8080/car/get2/100/张三
@RequestMapping("get2/{id}/{name}")
//{x}--通过{}获取访问路径中携带的参数,并且交给变量x保存
//@PathVariable -- 获取{}中间变量的值
public String get2(@PathVariable Integer id,
@PathVariable String name){
return id+name;
}
//http://localhost:8080/car/get3/100/张三/red/9.9
@RequestMapping("get3/{a}/{b}/{c}/{d}")
public String get3(@PathVariable Integer a,
@PathVariable String b,
@PathVariable String c,
@PathVariable double d){
return a+b+c+d ;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<a href="http://localhost:8080/car/get?id=100&name=张三">解析get的参数 </a>
<a href="http://localhost:8080/car/get2/100/张三">解析restful风格的参数</a>
<a href="http://localhost:8080/car/get3/100/张三/red/9.9">练习解析restful风格的参数</a>
</body>
</html>
二,SpringMVC解析post的请求参数
–0,项目结构
–1,准备form表单
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
body{
font-size: 17px;/* 字号 */
background-color: lightgray;
}
/* 输入框 */
.a{
width: 320px; /* 宽度*/
height: 50px; /* 高度 */
font-size: 20px; /* 字号 */
}
/* 保存按钮 */
input[type="submit"]{
/* 背景色 字的颜色 边框颜色 宽度 高度 */
background-color: #0000FF;
border-color: #0000FF;
color: white;
width: 100px;
height: 50px;
font-size: 20px; /* 字号 */
}
/* 取消按钮 */
input[type="button"]{
/* 背景色 字的颜色 边框颜色 宽度 高度 */
background-color: #FF69B4;
border-color: #FF69B4;
color: white;
width: 100px;
height: 50px;
font-size: 20px; /* 字号 */
}
</style>
</head>
<body>
<a href="http://localhost:8080/car/get?id=100&name=张三">解析get的参数 </a>
<a href="http://localhost:8080/car/get2/100/张三">解析restful风格的参数</a>
<a href="http://localhost:8080/car/get3/100/张三/red/9.9">练习解析restful风格的参数</a>
<!-- 利用表单,向服务器发送数据,
默认是get提交,通过method属性修改提交方式
action属性,指定提交的位置
-->
<form method="post" action="http://localhost:8080/stu/add">
<table>
<tr>
<td>
<h2>学生信息管理系统MIS</h2>
</td>
</tr>
<tr>
<td>姓名:</td>
</tr>
<tr>
<td>
<input class="a" type="text" placeholder="请输入姓名" name="name">
</td>
</tr>
<tr>
<td>年龄:</td>
</tr>
<tr>
<td>
<input class="a" type="number" placeholder="请输入年龄" name="age">
</td>
</tr>
<tr>
<td>
性别:(单选框)
<input type="radio" name="sex" value="1"/>男
<input type="radio" name="sex" value="0"/>女
</td>
</tr>
<tr>
<td>
爱好:(多选)
<input type="checkbox" name="hobby" value="ppq"/>乒乓球
<input type="checkbox" name="hobby" value="ps"/>爬山
<input type="checkbox" name="hobby" value="cg"/>唱歌
</td>
</tr>
<tr>
<td>
学历:(下拉框)
<select name="edu">
<option value="1">本科</option>
<option value="2">专科</option>
<option value="3">博士</option>
</select>
</td>
</tr>
<tr>
<td>
入学日期:
<input type="date" name="intime"/>
</td>
</tr>
<tr>
<td>
<input type="submit" value="保存"/>
<input type="button" value="取消"/>
</td>
</tr>
</table>
</form>
</body>
</html>
–2,准备Student类
package cn.tedu.pojo;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Arrays;
import java.util.Date;
//是Model层,用来封装数据,就是一个pojo(封装的属性+get/set)
public class Student {
//属性(成员变量):变量类型 变量名
//提交数据的类型 页面上name属性的值
private String name ;
private Integer age ;//避免了一些异常
private Integer sex ;
private String[] hobby ;
private Integer edu ;
//浏览器上提交的日期默认是String类型,2012/8/12,报错400
//@DateTimeFormat把String的日期转成Date日期
//pattern属性规定了日期的格式y表示年M表示月d表示日
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date intime;
//get set tostring
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;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public Integer getEdu() {
return edu;
}
public void setEdu(Integer edu) {
this.edu = edu;
}
public Date getIntime() {
return intime;
}
public void setIntime(Date intime) {
this.intime = intime;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
", hobby=" + Arrays.toString(hobby) +
", edu=" + edu +
", intime=" + intime +
'}';
}
}
–3,准备StudentController类
package cn.tedu.controller;
import cn.tedu.pojo.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//是C层,控制层,用来接受请求和给出响应
@RestController
@RequestMapping("stu")
public class StudentController {
@RequestMapping("add")
public Object add(Student s){
//TODO 实现入库insert
return s;
}
}
–4,利用jdbc把接受到的参数入库
操作cgb2106的库, 创建tb_student表(参考Student类)
CREATE TABLE tb_student(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50),
age INT,
sex INT,
hobby VARCHAR(100),
edu INT,
intime DATE
)
<?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">
<parent>
<artifactId>cgb2106boot03</artifactId>
<groupId>cn.tedu</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>day14</artifactId>
<dependencies>
<!--添加jdbc的jar包依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
</dependencies>
</project>
package cn.tedu.controller;
import cn.tedu.pojo.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;
//是C层,控制层,用来接受请求和给出响应
@RestController
@RequestMapping("stu")
public class StudentController {
@RequestMapping("add")
public Object add(Student s) throws Exception {
//TODO 利用jdbc,实现入库
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
String url="jdbc:mysql:///cgb2106?characterEncoding=utf8";
Connection conn = DriverManager.getConnection(url,"root","root");
//获取传输器
String sql = "insert into tb_student values(null,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
//给SQL设置参数
ps.setObject(1,s.getName());
ps.setObject(2,s.getAge());
ps.setObject(3,s.getSex());
//s.getHobby()得到一个数组,不能直接存入数据库,需要变成串入库
ps.setObject(4, Arrays.toString( s.getHobby() ) ) ;
ps.setObject(5,s.getEdu());
ps.setObject(6,s.getIntime());
//执行SQL
ps.executeUpdate();//执行增删改的SQL
System.out.println("数据插入成功!");
return s;
}
}
–5,测试
–6,总结
三,Git
–1,概述
是一个版本控制产品,用来实现资源的版本控制.
可以把资源随时上传到Git上,可以随时拉取下载
好处: 快速恢复到历史版本. 容错性高.
远程仓库: 是指 Gitee官网 的网址,存你已经传上去的资源
本地仓库: 是指你磁盘里的一个路径,存你即将要上传的资源
本地索引: 是指将要提交的数据建立索引,方便查找定位
工作空间: 保存了资源的位置
过程: 工作空间 -> 本地索引 -> 本地仓库 -> 远程仓库
–2,常用命令
add: 把工作空间的资源,添加到 本地索引
commit: 把本地索引的资源 提交到 本地仓库
push: 把本地仓库的资源 推送到 远程仓库
pull/clone: 把资源从远程仓库下载下来
–3,使用步骤
1, 安装Git软件
2, 在Gitee官网注册账号,使用账号上传资源
3, 创建本地仓库, 就是在你的磁盘里建一个文件夹,存放即将上传的资源
仅供参考: D:\workspace\gitee\cgb2106
4, 创建远程仓库, 去Gitee官网创建,存本地仓库上传的资源
Gitee官网右上角的加号,点新建仓库,设置仓库名称选成开源,ok
5, 需要在本地仓库那里,执行一些Git命令.
git config --global user.name "cgblpx" #设置了Gitee注册的用户名
git config --global user.email "2250432165@qq.com" #设置了Gitee注册的邮箱
git config --list # 查看设置信息
git init #初始化一个Git的环境
#在你的本地仓库创建一个文件,准备上传它
git add 1.txt #添加,从工作空间到本地索引
git commit -m "first commit" #从本地索引提交到本地仓库
git remote add origin https://gitee.com/cgblpx/cgb2106test.git
#添加到指定远程仓库里
git push -u origin master #从本地仓库推送到远程仓库
Username for 'https://gitee.com': #输入自己注册的账号
Password for 'https://cgblpx@gitee.com': #输入自己注册的密码
–4,检查
刷新Gitee官网就有刚传上去的资源啦
- 1
–5,日常操作
1, 把你要提交的资源拷贝到 本地仓库
2, 在本地仓库处, 执行以下Git命令提交资源
3, 把远程仓库的资源下载到本地
git add .
git commit -m "test"
git push -u origin master
git clone 再加上要下载的资源的网址
四
一,Spring
–1,概述
功能非常丰富,核心的功能是: IOC DI AOP
IOC : 是控制反转,指 把创建对象的过程交给了Spring
DI : 是依赖注入,指把对象间的依赖关系 自动维护
AOP : 是补充了OOP的不足
–2,IOC的XML实现方式
是指把创建对象管理对象的过程交给了Spring框架
File-New-Module-Maven-next-输入ModuleName-ok
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
配置Bean的信息
id用来作为这个bean的唯一标识,class用来描述类的全路径
-->
<bean id="hello" class="cn.tedu.spring.Hello"></bean>
</beans>
package cn.tedu.test;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
@Test
public void get(){
//1,读取配置文件
ClassPathXmlApplicationContext spring =
new ClassPathXmlApplicationContext(
"spring-config.xml");
//2,直接getBean
Object o = spring.getBean("hello");
System.out.println(o);//cn.tedu.spring.Hello@45752059
}
}
–3,IOC的注解实现方式
package cn.tedu.ioc;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
@Component("a")//自动完成IOC,自己指定bean的名字a -> {"a",new User()}
//@Component //默认的bean的名字,user
//@Component自动完成IOC, -> {"user",new User()}
//@Controller //spring提供的,用来ioc
//@Service //spring提供的,用来ioc
public class User {
public void get(){
System.out.println(123);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--
配置Bean的信息
id用来作为这个bean的唯一标识,class用来描述类的全路径
IOC->{ "hello" , new Hello() }
-->
<bean id="hello" class="cn.tedu.spring.Hello"></bean>
<!--
配置包扫描
base-package指定一个包的路径,扫描范围可以自己定
-->
<context:component-scan base-package="cn.tedu"></context:component-scan>
</beans>
package cn.tedu.test;
import cn.tedu.ioc.User;
import cn.tedu.spring.Hello;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
@Test
public void get(){
//1,读取配置文件
ClassPathXmlApplicationContext spring =
new ClassPathXmlApplicationContext(
"spring-config.xml");
//2,直接getBean
Object o = spring.getBean("hello");
System.out.println(o);//cn.tedu.spring.Hello@45752059
//调用子类的方法--向下转型/造型
Hello h = (Hello) o ;
h.get();
//获取注解的bean
User u = (User) spring.getBean("a");
System.out.println(u);//cn.tedu.ioc.User@28f3b248
}
}
4,Spring的DI 依赖注入
–1,概述
是指对象间的依赖关系,可以由框架来完成
–2,简单模拟
package cn.tedu.di;
public class Dept {
String name="java软件开发一部";
@Override
public String toString() {
return "Dept{" +
"name='" + name + '\'' +
'}';
}
}
package cn.tedu.di;
public class Emp {
String name="jack";
//绑定两个类间的关系
private Dept d ;
public Dept getD() {
return d;
}
public void setD(Dept d) {
this.d = d;
}
@Override
public String toString() {
return "Emp{" +
"name='" + name + '\'' +
", d=" + d +
'}';
}
}
package cn.tedu.test;
import cn.tedu.di.Dept;
import cn.tedu.di.Emp;
import org.junit.jupiter.api.Test;
public class Test1 {
@Test
public void di(){
Dept d = new Dept();
System.out.println(d);//Dept{name='java软件开发一部'}
Emp e = new Emp();
System.out.println(e);//Emp{name='jack', d=null}
//di--把两个对象间的关系依赖注入
e.setD(d);
System.out.println(e);
//已经实现了di的效果,在查询e把关联的d的信息也查到了
//Emp{name='jack', d=Dept{name='java软件开发一部'}}
}
}
–3,使用Spring实现DI
package cn.tedu.di2;
import org.springframework.stereotype.Component;
@Component
public class Teacher {
String name = "tony";
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
'}';
}
}
package cn.tedu.di2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Student {
String name = "蔡徐坤";
@Autowired //di
Teacher t ;
@Override
public String toString() {
return "Student{" +
"t=" + t +
", name='" + name + '\'' +
'}';
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--包扫描:扫描指定包路径下的所有类,谁有ioc的注解就new谁 -->
<context:component-scan base-package="cn.tedu.di2"></context:component-scan>
</beans>
@Test
public void di2(){
//1,读取xml文件
ClassPathXmlApplicationContext spring = new
ClassPathXmlApplicationContext(
"spring-config.xml");
//2,getBean
Object o = spring.getBean("student");
//di:查学生信息的同时也查到了老师信息,两个对象之间的依赖注入
//Student{t=Teacher{name='tony'}, name='蔡徐坤'}
System.out.println(o);
}
五
一,Lombok
–1,概述
简化了Model层的代码的编写.
以前pojo类/实体类,需要自己提供set get toString equals hashCode
Lombok通过各种注解,简化了以上操作
@Data会自动生成set get toString equals hashCode
@NoArgsConstructor自动生成无参构造
@AllArgsConstructor自动生成全参构造
@Accessors(chain = true) //开启链式编程
–2,使用步骤
Settings-选Plugins-搜插件名-install
- 1
2, 修改pom.xml文件,添加lombok的jar包依赖
<!--添加jar包依赖-->
<dependencies>
<!--添加lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
用lombok前
package cn.tedu.pojo;
public class Car {
private Integer id;
private String name;
private String color;
private Double price;
//get set tostring
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"id=" + id +
", name='" + name + '\'' +
", color='" + color + '\'' +
", price=" + price +
'}';
}
}
用lombok后
package cn.tedu.pojo;
//使用lombok
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data//自动生成get set tostring hashcode equals
@NoArgsConstructor//自动生成无参构造
@AllArgsConstructor//自动生成全参构造
@Accessors(chain = true)//开启链式编程
public class Student {
private Integer id;
private String name;
private String sex;
}
package cn.tedu.test;
import cn.tedu.pojo.Car;
import cn.tedu.pojo.Student;
import org.junit.jupiter.api.Test;
public class Test1 {
//测试lombok
@Test
public void get2(){
Student s = new Student();
Student s2 = new Student(200,"rose","女");
// s.setId(100);
// s.setName("jack");
// s.setSex("男");
//对set()可以使用lombok的链式编程
s.setId(100).setName("jack").setSex("男");
System.out.println(s);
System.out.println(s.getId()+s.getName()+s.getSex());
}
//测试Car
@Test
public void get(){
Car c = new Car();
c.setName("BMW");
String s = c.getName();
System.out.println(s);
c.setId(100);//自动装箱
Integer i = c.getId() ;
System.out.println(i);
System.out.println( c.getId() );
}
}
二,热部署
–1,概述
以前服务器改完代码,每次都需要重启服务器
现在只需要改完了重新build就行
–2,步骤
<!--添加热部署的jar-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>2.5.3</version>
</dependency>
按下组合键: ctrl + shift + alt + / 或者 ctrl + alt + a, 选中Registry, 选中自动编译, ok
- 1
创建RunApp启动类
package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RunApp {
public static void main(String[] args) {
SpringApplication.run(RunApp.class);
}
}
创建StuController,接受请求处理响应
package cn.tedu.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("stu")
public class StuController {
@RequestMapping("get")
public String get(){
//热部署:改变成新的数据,也不必重启服务器了,只是build就可以啦
return "xyz";
}
}
http://localhost:8080/stu/get
- 1
三,两框架整合
–0,项目结构
–1,概述
–2,创建网页
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试 两个框架整合</title>
</head>
<body>
<a href="http://localhost:8080/car/get">请求服务器的数据</a>
</body>
</html>
–3,创建RunApp类,启动服务器
package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//SpringBoot自动配置了包扫描:默认基于启动类所在的包
public class RunApp {
public static void main(String[] args) {
SpringApplication.run(RunApp.class);
}
}
–4,创建Car类
<?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">
<parent>
<artifactId>cgb2106boot03</artifactId>
<groupId>cn.tedu</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>day1602</artifactId>
<dependencies>
<!--导入lombok简化pojo-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
</project>
package cn.tedu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data //自动生成get set tostring...
@NoArgsConstructor //自动生成无参构造
@AllArgsConstructor//自动生成全参构造
@Accessors(chain = true)//开启链式编程
public class Car {
private String name;
private String color;
private Double price;
}
–5,创建CarController类
package cn.tedu.controller;
import cn.tedu.pojo.Car;
import cn.tedu.service.CarServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("car")
public class CarController {
@Autowired //想要调用service层的代码--di
private CarServiceImpl carService;
@RequestMapping("get")
public Object get(){
return carService.get(); //把结果给浏览器返回
}
}
–6,创建CarService接口
package cn.tedu.service;
import cn.tedu.pojo.Car;
//定义接口
public interface CarService {
//接口里的方法都是抽象方法,而且都是public的
Car get(); //获取汽车数据
// void add(Car c) ;//新增汽车数据
}
–7,创建CarServiceImpl实现类
package cn.tedu.service;
import cn.tedu.pojo.Car;
import org.springframework.stereotype.Component;
@Component
//实现了接口后,要重写抽象方法
public class CarServiceImpl implements CarService{
public Car get(){
Car c = new Car();
//lombok的链式编程
c.setName("保时捷").setColor("红色").setPrice(641000.0);
return c;
}
}
–8,测试
1, 启动服务器
2, 打开浏览器执行前端HTML网页,发起请求,请求服务器的数据,
3, 服务器收到请求后响应了准备好的数据
–9,总结
六
一,AOP
–1,概述
是一个面向切面编程的思想,补充了OOP的不足.
实现的效果: 对方法的增强,本质上就是在执行方法的前后添加功能.
经典的使用场景: 统计性能分析 / 权限管理 / 事务管理 / 日志 / 缓存…
好处: 让程序员更专注业务代码本身
切面: 本质上就是一个类
通知: 本质上就是一个方法,定义一些功能
分为:前置通知,后置通知和环绕通知,返回后通知,异常通知
前置通知 : 是方法执行前要执行的功能
后置通知 : 是方法执行后要执行的功能
环绕通知 : 是方法执行 前 后都要执行的功能
切点: 指定哪些类里的哪些方法要用 通知的功能
常用AOP注解:
@Aspect : 表示是一个切面类
@Before : 表示是一个前置通知
@After : 表示是一个后置通知
@Around : 表示是一个环绕通知
@PointCut : 表示切点
–2,步骤
<!--添加aop依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package cn.tedu.service;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Service;
@Service //ioc
@Aspect//标记着这是一个aop的类:切面(由切点和组成)
public class AopAspect {
//1,切点(指定具体要用通知的类和方法)
//切点表达式:*是通配符 ..表示0~n个
//方法返回值/包路径/子包/类名/方法名/参数列表
@Pointcut("execution( * cn.tedu.service..*.*(..))")
public void point(){}
//2,通知(是一个方法自定义功能)
@Around("point()")//是一个环绕通知
public Object doAround(ProceedingJoinPoint joinPoint)
throws Throwable {
long time = System.currentTimeMillis();//计时开始
//去执行你的业务方法--joinPoint连接点
Object o = joinPoint.proceed();
time = System.currentTimeMillis()-time;//计时结束
String methodname = joinPoint.getTarget().getClass().getName()//获取类名
+"."+joinPoint.getSignature().getName();//获取方法名
System.out.println(methodname+"方法执行时间是: "+time);
return o ;
}
}
启动服务器 , 访问指定包 里的资源时 , 就会自动触发切面中通知的功能.
二,Ajax
–1,概述
全称 异步的js and xml ,
好处: 异步访问 , 局部刷新
–2,步骤
语法:axios.get(url).then( a=>( a表示服务器返回的结果 ) )
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试 vue提供的ajax技术</title>
<!-- 1. 导入vue.js和axios.js -->
<script src="vue.js"></script>
<script src="axios.min.js"></script>
<!-- 发起ajax请求,异步访问,局部刷新-->
</head>
<body>
<!-- 2. 准备数据渲染区,利用插值表达式获取值 -->
<div id="app">
123{{info}}
</div>
<!-- 3. 创建Vue对象 -->
<script>
new Vue({
el : "#app", // 挂载点
data : { //数据区
info : ' '
},
mounted : function(){//发起ajax请求
//ajax 访问 服务器的数据
axios.get('http://localhost:8080/car/get').then(
//箭头语法,其中a表示服务器返回的数据
a => (
//修改info的值,a.data是固定写法用来获取a的值
this.info = a.data
)
)
}
})
</script>
</body>
</html>
添加一个注解,@CrossOrigin //放行JS的请求–跨域的解决方案
访问网页,网页会直接发起ajax请求,请求服务器的数据.服务器把数据返回交给ajax继续解析,最终实现局部刷新网页.
三,Mybatis
–1,概述
底层封装了JDBC , 对数据库可以进行操作 , 是一个优秀的持久层框架
好处: 简化了JDBC的开发步骤, 自动完成ORM映射
–2,核心资源
mybatis-config.xml 配置了事务管理,数据源
XxxMapper.xml 存放大量的CRUD的SQL语句
会话工厂SqlSessionFactory : 产生会话
会话SqlSession : 执行SQL语句
是指对象关系映射.
把表里的字段的值 查到 自动交给 类里的属性 保存
–3,入门案例
<?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">
<parent>
<artifactId>cgb2106boot03</artifactId>
<groupId>cn.tedu</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>day17</artifactId>
<dependencies>
<!--mybatis依赖包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--jdbc依赖包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的核心配置文件,配置了事务管理,数据源 -->
<configuration>
<!--environments可以配置多个数据库的连接信息,default指定默认的环境-->
<environments default="test">
<environment id="test">
<!--使用的事务管理器-->
<transactionManager type="JDBC"></transactionManager>
<!--配置了数据源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisdb?characterEncoding=utf8&serverTimezone=Asia/Shanghai" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--这个文件是映射文件,写SQL的
namespace用来作为一个mapper.xml文件的唯一标识
-->
<mapper namespace="userMapper">
<!-- 查id=1的用户信息
id是这条SQL的唯一标识
resultType的值用来封装查到的结果,ORM
-->
<select id="getById" resultType="cn.tedu.pojo.User">
select * from user where id=1
</select>
</mapper>
package cn.tedu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
//注意:::属性的名 和 表里的字段名 必须一致,否则无法ORM
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class User {
private Integer id;
private String name;
private String addr;
private Integer age;
}
七
一,Mybatis入门案例
–0,导入mybatis的jar包
<?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">
<parent>
<artifactId>cgb2106boot03</artifactId>
<groupId>cn.tedu</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>day17</artifactId>
<dependencies>
<!--mybatis依赖包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--jdbc依赖包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
</dependencies>
</project>
–1,核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的核心配置文件,配置了事务管理,数据源 -->
<configuration>
<!--environments可以配置多个数据库的连接信息,default指定默认的环境-->
<environments default="test">
<environment id="test">
<!--使用的事务管理器-->
<transactionManager type="JDBC"></transactionManager>
<!--配置了数据源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisdb?characterEncoding=utf8&serverTimezone=Asia/Shanghai" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="UserMapper.xml"></mapper>
</mappers>
</configuration>
–2,映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--这个文件是映射文件,写SQL的
namespace用来作为一个mapper.xml文件的唯一标识
-->
<mapper namespace="userMapper">
<!-- 查id=1的用户信息
id是这条SQL的唯一标识
resultType的值用来封装查到的结果,ORM
-->
<select id="getById" resultType="cn.tedu.pojo.User">
select * from user where id=1
</select>
</mapper>
–3,创建User类
package cn.tedu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
//注意:::属性的名 和 表里的字段名 必须一致,否则无法ORM
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class User {
private Integer id;
private String name;
private String addr;
private Integer age;
}
–4,测试类
package cn.tedu.test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
public class Test1 {
@Test
public void get() throws IOException {
InputStream in = Resources.getResourceAsStream(
"mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(in);
SqlSession session = factory.openSession();
Object o = session.selectOne("userMapper.getById");
//User(id=1, name=hanmeimei, addr=北京, age=28)
System.out.println(o);
}
}
5,总结
二,Mybatis的练习
–1,修改映射文件UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--这个文件是映射文件,写SQL的
namespace用来作为一个mapper.xml文件的唯一标识
-->
<mapper namespace="userMapper">
<!--
面试题:SQL动态获取参数时,可以用#或者$
$ 底层用了低级传输器,可能发生SQL注入攻击,低效,不拼串,可能发生SQL语法错误
# 底层用了高级传输器,安全,高效,会自动拼接字符串 'xiongda'
-->
<!-- 查id=1的用户信息
id是这条SQL的唯一标识
resultType的值用来封装查到的结果,ORM
-->
<select id="getById" resultType="cn.tedu.pojo.User">
select * from user where id=${id}
</select>
<!-- 查询所有user -->
<select id="getAll" resultType="cn.tedu.pojo.User">
select * from user
</select>
<!-- 查询hanmeimei的,固定语法#{??}用来解析SQL的参数-->
<select id="getByName" resultType="cn.tedu.pojo.User">
select * from user where name=#{name}
</select>
</mapper>
–2,修改测试类
package cn.tedu.test;
import cn.tedu.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test1 {
@Test
public void get() throws IOException {
//读取配置文件
InputStream in = Resources.getResourceAsStream(
"mybatis-config.xml");
//创建会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(in);
//开启会话,准备执行SQL
SqlSession session = factory.openSession();
//定位SQL(namespace的值.id的值),并执行
//selectOne执行查询的SQL,并只会返回一个结果
Object o = session.selectOne("userMapper.getById",2);
//User(id=1, name=hanmeimei, addr=北京, age=28)
System.out.println(o);
//定位SQL(namespace的值.id的值),并执行
//selectList执行查询的SQL,并返回多个结果
List<User> list = session.selectList("userMapper.getAll");
for(User u : list){
System.out.println(u);
}
//定位SQL(namespace的值.id的值),并执行,并给SQL传入参数
User u = session.selectOne(
"userMapper.getByName","xiongda");
System.out.println(u);
}
}
–3,总结
三,优化配置
–1,别名
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的核心配置文件,配置了事务管理,数据源 -->
<configuration>
<!--配置别名,给指定类起一个指定的别名-->
<typeAliases>
<typeAlias type="cn.tedu.pojo.User" alias="User"></typeAlias>
</typeAliases>
<!--environments可以配置多个数据库的连接信息,default指定默认的环境-->
<environments default="test">
<environment id="test">
<!--使用的事务管理器-->
<transactionManager type="JDBC"></transactionManager>
<!--配置了数据源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisdb2?characterEncoding=utf8&serverTimezone=Asia/Shanghai" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="UserMapper.xml"></mapper>
</mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--这个文件是映射文件,写SQL的
namespace用来作为一个mapper.xml文件的唯一标识
-->
<mapper namespace="userMapper">
<!--
面试题:SQL动态获取参数时,可以用#或者$
$ 底层用了低级传输器,可能发生SQL注入攻击,低效,不拼串,可能发生SQL语法错误
# 底层用了高级传输器,安全,高效,会自动拼接字符串 'xiongda'
-->
<!-- 查id=1的用户信息
id是这条SQL的唯一标识
resultType的值用来封装查到的结果,ORM
-->
<select id="getById" resultType="User">
select * from user where id=${id}
</select>
<!-- 查询所有user -->
<select id="getAll" resultType="User">
select * from user
</select>
<!-- 查询hanmeimei的,固定语法#{??}用来解析SQL的参数-->
<select id="getByName" resultType="User">
select * from user where name=#{name}
</select>
</mapper>
四,接口开发
–1,概述
为了优化定位SQL的字符串拼接过程, namespace的值.id的值
步骤:
0, 创建接口 创建方法
1, namespace的值 是接口的全路径
2, id的值 是接口里的方法名
–2,使用
package cn.tedu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
//完成ORM,属性名 必须和字段名 一致
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Dept {
private Integer id ;
private String dname ;
private String loc ;
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="deptMapper">
<select id="getById" resultType="Dept">
select * from dept where id=1
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的核心配置文件,配置了事务管理,数据源 -->
<configuration>
<!--配置别名,给指定类起一个指定的别名-->
<typeAliases>
<typeAlias type="cn.tedu.pojo.User" alias="User"></typeAlias>
<typeAlias type="cn.tedu.pojo.Dept" alias="Dept"></typeAlias>
</typeAliases>
<!--environments可以配置多个数据库的连接信息,default指定默认的环境-->
<environments default="test">
<environment id="test">
<!--使用的事务管理器-->
<transactionManager type="JDBC"></transactionManager>
<!--配置了数据源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisdb2?characterEncoding=utf8&serverTimezone=Asia/Shanghai" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="UserMapper.xml"></mapper>
<mapper resource="DeptMapper.xml"></mapper>
</mappers>
</configuration>
package cn.tedu.test;
import cn.tedu.pojo.Dept;
import cn.tedu.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test1 {
@Test
public void get() throws IOException {
//读取配置文件
InputStream in = Resources.getResourceAsStream(
"mybatis-config.xml");
//创建会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(in);
//开启会话,准备执行SQL
SqlSession session = factory.openSession();
//定位SQL(namespace的值.id的值),并执行
//selectOne执行查询的SQL,并只会返回一个结果
Object o = session.selectOne("userMapper.getById",2);
//User(id=1, name=hanmeimei, addr=北京, age=28)
System.out.println(o);
//定位SQL(namespace的值.id的值),并执行
//selectList执行查询的SQL,并返回多个结果
List<User> list = session.selectList("userMapper.getAll");
for(User u : list){
System.out.println(u);
}
//定位SQL(namespace的值.id的值),并执行,并给SQL传入参数
User u = session.selectOne(
"userMapper.getByName","xiongda");
System.out.println(u);
//定位SQL(namespace的值.id的值)
Dept d = session.selectOne("deptMapper.getById");
System.out.println(d);
}
}
–3,改造
package cn.tedu.dao;
import cn.tedu.pojo.Dept;
//接口的全路径=映射文件中namespace的值
//接口的方法名=映射文件中id的值
public interface DeptMapper {
Dept getById();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace=接口的全路径 -->
<mapper namespace="cn.tedu.dao.DeptMapper">
<!--id=接口里的方法名-->
<select id="getById" resultType="Dept">
select * from dept where id=1
</select>
</mapper>
package cn.tedu.test;
import cn.tedu.dao.DeptMapper;
import cn.tedu.pojo.Dept;
import cn.tedu.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test1 {
@Test
public void get() throws IOException {
//读取配置文件
InputStream in = Resources.getResourceAsStream(
"mybatis-config.xml");
//创建会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(in);
//开启会话,准备执行SQL
SqlSession session = factory.openSession();
//定位SQL(namespace的值.id的值),并执行
//selectOne执行查询的SQL,并只会返回一个结果
Object o = session.selectOne("userMapper.getById",2);
//User(id=1, name=hanmeimei, addr=北京, age=28)
System.out.println(o);
//定位SQL(namespace的值.id的值),并执行
//selectList执行查询的SQL,并返回多个结果
List<User> list = session.selectList("userMapper.getAll");
for(User u : list){
System.out.println(u);
}
//定位SQL(namespace的值.id的值),并执行,并给SQL传入参数
User u = session.selectOne(
"userMapper.getByName","xiongda");
System.out.println(u);
//定位SQL(namespace的值.id的值)
// Dept d = session.selectOne("deptMapper.getById");
// System.out.println(d);
//获取了指定的接口
DeptMapper mapper = session.getMapper(DeptMapper.class);
//调用接口里的方法
Dept dd = mapper.getById();
System.out.println(dd);
}
}
五,练习接口开发
–1,修改 接口文件
package cn.tedu.dao;
import cn.tedu.pojo.Dept;
import java.util.List;
//接口的全路径=映射文件中namespace的值
//接口的方法名=映射文件中id的值
public interface DeptMapper {
Dept getById(); //根据id查
List<Dept> getByName(String dname);//根据名字查
void save(Dept dept);//新增部门记录
}
–2,修改 映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace=接口的全路径 -->
<mapper namespace="cn.tedu.dao.DeptMapper">
<!--新增部门记录-->
<insert id="save">
insert into dept values(#{id},#{dname},#{loc})
</insert>
<select id="getByName" resultType="Dept">
select * from dept where dname=#{dname};
</select>
<!--id=接口里的方法名-->
<select id="getById" resultType="Dept">
select * from dept where id=1
</select>
</mapper>
–3,修改 测试文件
package cn.tedu.test;
import cn.tedu.dao.DeptMapper;
import cn.tedu.pojo.Dept;
import cn.tedu.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test1 {
@Test
public void get() throws IOException {
//读取配置文件
InputStream in = Resources.getResourceAsStream(
"mybatis-config.xml");
//创建会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(in);
//开启会话,准备执行SQL
SqlSession session = factory.openSession();
//定位SQL(namespace的值.id的值),并执行
//selectOne执行查询的SQL,并只会返回一个结果
Object o = session.selectOne("userMapper.getById",2);
//User(id=1, name=hanmeimei, addr=北京, age=28)
System.out.println(o);
//定位SQL(namespace的值.id的值),并执行
//selectList执行查询的SQL,并返回多个结果
List<User> list = session.selectList("userMapper.getAll");
for(User u : list){
System.out.println(u);
}
//定位SQL(namespace的值.id的值),并执行,并给SQL传入参数
User u = session.selectOne(
"userMapper.getByName","xiongda");
System.out.println(u);
//定位SQL(namespace的值.id的值)
// Dept d = session.selectOne("deptMapper.getById");
// System.out.println(d);
//获取了指定的接口
DeptMapper mapper = session.getMapper(DeptMapper.class);
//调用接口里的方法
Dept dd = mapper.getById();
System.out.println(dd);
List<Dept> ds = mapper.getByName("java教研部");
for (Dept d : ds) {
System.out.println(d);
}
Dept dept = new Dept();
dept.setId(100).setDname("ios开发部").setLoc("上海");
mapper.save(dept);
//mybatis不会自动提交事务,增删改需要自己提交事务
session.commit();
}
}
六,动态SQL
–1,概述
利用mybatis框架提供一些标签,完成SQL的拼接
常用标签 :
sql : 提取SQL片段
include : 引入指定的SQL片段
if : 用来判断,满足条件才拼接SQL
–2,修改映射文件,实现动态SQL
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace=接口的全路径 -->
<mapper namespace="cn.tedu.dao.DeptMapper">
<!-- 提取SQL片段,提高SQL片段复用性 -->
<sql id="cols">
id,dname,loc
</sql>
<!-- 引用SQL片段 -->
<select id="getByName" resultType="Dept">
select
<include refid="cols"></include>
from dept
<if test="dname != null">
where dname=#{dname}
</if>
</select>
<!--id=接口里的方法名-->
<select id="getById" resultType="Dept">
select
<include refid="cols"></include>
from dept where id=1
</select>
<!--新增部门记录-->
<insert id="save">
insert into dept values(#{id},#{dname},#{loc})
</insert>
</mapper>
八
一,动态SQL
–1,foreach标签
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace=接口的全路径 -->
<mapper namespace="cn.tedu.dao.DeptMapper">
<!-- 提取SQL片段,提高SQL片段复用性 -->
<sql id="cols">
id,dname,loc
</sql>
<!-- delete from dept where id in(1,2,3)-->
<delete id="delete">
delete from dept where id in(
/*foreach用来完成遍历
collection表示要遍历哪种集合里的数据,值是固定值:array/list/Map.key
item表示即将遍历到的数据,separator是分隔符,#{ids}获取遍历到的数据
*/
<foreach collection="array" item="ids" separator=",">
#{ids}
</foreach>
)
</delete>
<!-- 引用SQL片段 -->
<select id="getByName" resultType="Dept">
select
<include refid="cols"></include>
from dept
<if test="dname != null">
where dname=#{dname}
</if>
</select>
<!--id=接口里的方法名-->
<select id="getById" resultType="Dept">
select
<include refid="cols"></include>
from dept where id=1
</select>
<!--新增部门记录-->
<insert id="save">
insert into dept values(#{id},#{dname},#{loc})
</insert>
</mapper>
package cn.tedu.dao;
import cn.tedu.pojo.Dept;
import java.util.List;
//接口的全路径=映射文件中namespace的值
//接口的方法名=映射文件中id的值
public interface DeptMapper {
Dept getById(); //根据id查
List<Dept> getByName(String dname);//根据名字查
void save(Dept dept);//新增部门记录
void delete(int[] a);//删除
}
package cn.tedu.test;
import cn.tedu.dao.DeptMapper;
import cn.tedu.pojo.Dept;
import cn.tedu.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test1 {
@Test
public void get() throws IOException {
//读取配置文件
InputStream in = Resources.getResourceAsStream(
"mybatis-config.xml");
//创建会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(in);
//开启会话,准备执行SQL
SqlSession session = factory.openSession();
//定位SQL(namespace的值.id的值),并执行
//selectOne执行查询的SQL,并只会返回一个结果
Object o = session.selectOne("userMapper.getById",2);
//User(id=1, name=hanmeimei, addr=北京, age=28)
System.out.println(o);
//定位SQL(namespace的值.id的值),并执行
//selectList执行查询的SQL,并返回多个结果
List<User> list = session.selectList("userMapper.getAll");
for(User u : list){
System.out.println(u);
}
//定位SQL(namespace的值.id的值),并执行,并给SQL传入参数
User u = session.selectOne(
"userMapper.getByName","xiongda");
System.out.println(u);
//定位SQL(namespace的值.id的值)
// Dept d = session.selectOne("deptMapper.getById");
// System.out.println(d);
//获取了指定的接口
DeptMapper mapper = session.getMapper(DeptMapper.class);
//调用接口里的方法
Dept dd = mapper.getById();
System.out.println(dd);
List<Dept> ds = mapper.getByName(null);
for (Dept d : ds) {
System.out.println(d+"=================");
}
Dept dept = new Dept();
dept.setId(null).setDname("ios开发部").setLoc("上海");
mapper.save(dept);
//mybatis不会自动提交事务,增删改需要自己提交事务
session.commit();
mapper.delete(new int[]{103,104});
session.commit();
}
}
二,ResultMap
–1,概述
resultType只能完成简单的ORM,只能完成那些 字段名 和 属性名一致的情况
字段名 和 属性名 不一样的情况,resultType必须换成resultMap,否则无法ORM
–2,测试
CREATE TABLE `user_info` (
`id` int(11) NOT NULL auto_increment,
`user_name` varchar(20) default NULL,
`user_addr` varchar(20) default NULL,
`user_age` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
<?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">
<parent>
<artifactId>cgb2106boot03</artifactId>
<groupId>cn.tedu</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>day19</artifactId>
<dependencies>
<!--mybatis依赖包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--jdbc依赖包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的核心配置文件,配置了事务管理,数据源 -->
<configuration>
<!--environments可以配置多个数据库的连接信息,default指定默认的环境-->
<environments default="test">
<environment id="test">
<!--使用的事务管理器-->
<transactionManager type="JDBC"></transactionManager>
<!--配置了数据源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisdb2?characterEncoding=utf8&serverTimezone=Asia/Shanghai" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="userInfoMapper.xml"></mapper>
</mappers>
</configuration>
创建映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.tedu.dao.UserInfoMapper">
<!-- 查询所有 ,字段名和属性名不一样,resultType换成resultMap
resultType="cn.tedu.pojo.UserInfo"
-->
<!-- ORM:是指把字段的值查到以后 交给 同名属性保存
使用resultMap: 字段名 和 属性名 不一样
id是唯一标识 type是类的全路径
-->
<resultMap id="abc" type="cn.tedu.pojo.UserInfo">
<result column="user_name" property="userName"></result>
<result column="user_addr" property="userAddr"></result>
<result column="user_age" property="userAge"></result>
</resultMap>
<!--resultMap属性是解决了resultType解决不了的问题,引用指定的resultMap-->
<select id="selectList" resultMap="abc">
select * from user_info
</select>
</mapper>
package cn.tedu.dao;
import cn.tedu.pojo.UserInfo;
import java.util.List;
public interface UserInfoMapper {
List<UserInfo> selectList();//查询所有
}
package cn.tedu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class UserInfo {
private Integer id;
private String userName;
private String userAddr;
private Integer userAge;
}
package cn.tedu.test;
import cn.tedu.dao.UserInfoMapper;
import cn.tedu.pojo.UserInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test1 {
@Test
public void all() throws IOException {
InputStream in = Resources.getResourceAsStream(
"mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(in);
//true表示自动提交事务
SqlSession session = factory.openSession(true);
//获取指定接口
UserInfoMapper mapper = session.getMapper(UserInfoMapper.class);
//调用方法
List<UserInfo> list = mapper.selectList();
for (UserInfo uf : list) {
//UserInfo(id=1, userName=null, userAddr=null, userAge=null)
System.out.println(uf);
}
}
}
3,优化简化resultmap
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的核心配置文件,配置了事务管理,数据源 -->
<configuration>
<settings>
<!--开启驼峰规则,简化resultMap的编写-->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<!--environments可以配置多个数据库的连接信息,default指定默认的环境-->
<environments default="test">
<environment id="test">
<!--使用的事务管理器-->
<transactionManager type="JDBC"></transactionManager>
<!--配置了数据源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisdb2?characterEncoding=utf8&serverTimezone=Asia/Shanghai" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="userInfoMapper.xml"></mapper>
</mappers>
</configuration>
第二步:resultMap标签中添加新属性 autoMapping=“true”
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.tedu.dao.UserInfoMapper">
<!-- 查询所有 ,字段名和属性名不一样,resultType换成resultMap
resultType="cn.tedu.pojo.UserInfo"
-->
<!-- ORM:是指把字段的值查到以后 交给 同名属性保存
使用resultMap: 字段名 和 属性名 不一样
id是唯一标识 type是类的全路径
autoMapping="true"是开启了自动驼峰规则的匹配
-->
<resultMap autoMapping="true" id="abc" type="cn.tedu.pojo.UserInfo">
<!-- <result column="user_name" property="userName"></result>
<result column="user_addr" property="userAddr"></result>
<result column="user_age" property="userAge"></result>-->
</resultMap>
<!--resultMap属性是解决了resultType解决不了的问题,引用指定的resultMap-->
<select id="selectList" resultMap="abc">
select * from user_info
</select>
</mapper>
三,SSM整合
–0,准备表和数据
CREATE TABLE `car` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(10) default NULL,
`color` varchar(10) default NULL,
`price` double default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
–0,添加mybatis的jar包
<?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">
<parent>
<artifactId>cgb2106boot03</artifactId>
<groupId>cn.tedu</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>SSM01</artifactId>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
–1,创建前端HTML网页
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ssm</title>
</head>
<body>
<a href="http://localhost:8080/car/get">点我请求服务器的资源</a>
</body>
</html>
–2,创建启动类RunApp
package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//扫描dao层接口文件所在的包,框架自动生成实现类
@MapperScan("cn.tedu.dao")
public class RunApp {
public static void main(String[] args) {
SpringApplication.run(RunApp.class);
}
}
–3,创建配置文件application.yml
#是一个特殊的文件,特殊在这个文件将被springboot框架自动加载-开箱即用
#格式非常严格,k: v
#SpringBoot配置mysql信息
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///mybatisdb?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: root
#SpringBoot整合Mybatis配置
mybatis:
#指定UserMapper.xml文件的位置
mapper-locations: classpath:*.xml
#开启驼峰映射
configuration:
map-underscore-to-camel-case: true
–4,创建pojo类
package cn.tedu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.stereotype.Component;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)//lombok的链式编程
@Component //ioc
public class Car {
private Integer id;
private String name;
private String color;
private Double price;
}
–5,创建CarMapper接口
package cn.tedu.dao;
import cn.tedu.pojo.Car;
import java.util.List;
@Component//没有啥意义
public interface CarMapper {
List<Car> selectList(); //查询所有数据
}
–6,创建映射文件CarMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace的值=dao层接口的全路径-->
<mapper namespace="cn.tedu.dao.CarMapper">
<!--查询所有数据 id=接口中的方法名-->
<select id="selectList" resultType="cn.tedu.pojo.Car">
select * from car
</select>
</mapper>
–7,创建CarService接口
package cn.tedu.service;
import cn.tedu.pojo.Car;
import java.util.List;
public interface CarService {
List<Car> selectList(); //查询所有数据
}
–8,创建CarServiceImpl实现类
package cn.tedu.service;
import cn.tedu.dao.CarMapper;
import cn.tedu.pojo.Car;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service //ioc
public class CarServiceImpl implements CarService{
@Autowired //di依赖注解dao层,为了使用dao的功能
private CarMapper mapper;
@Override //查询所有数据
public List<Car> selectList() {
return mapper.selectList();
}
}
–9,创建CarController类
package cn.tedu.controller;
import cn.tedu.pojo.Car;
import cn.tedu.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController//相当于@Controller+@ResponseBody
@RequestMapping("car")
public class CarController {
@Autowired //di
private CarService carService ;
//查询所有数据
@RequestMapping("get")
public List<Car> selectList(){
return carService.selectList() ;
}
}
–10,测试
打开浏览器,访问服务器
–11,总结
更多推荐
所有评论(0)