IDEA创建项目
Create new project中
创建时项目必要的元素
创建后会少文件夹(在高版本中会直接创立好)
并且要单独任命为特殊文件夹
首先:创立Directory
其次:将java文件和recourse文件分别设置为Sources Root和Recourse Root文件(这里我设置过了所以没有第一个SR)
项目数据流程图
mybatis
介绍
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
orm映射的半自动化的持久层框架
ORM:Object Relation Mapping对象关系映射
java对象和数据库
java对象 (类、对象) 和 数据库 (表、记录、字段)
类 ==》 表
对象 ==》 记录
属性 ==》 字段
半自动化:做了几乎所有JDBC的事,但是sql创建需要开发人员来做。
持久层 :控制层、业务层、持久层(和数据库进行交互)
框架 :
第一步 在pom.xml中添加mybatis依赖
一个提供版本号的网站https://mvnrepository.com/
使用步骤:搜索mybatis
选一个使用频率最高的进入
然后往下拉就可以看见,复制到dependencise中
复制进去后artifactid和version会红,maven中刷新就好
Mysql的导入也是按照上面的步骤,搜索选择复制就OK。(别忘记刷新)
以上完成后Dependencise中会出现两个文件
第二步 编写配置文件 内容为连接数据库并调用映射器(sql语句)
<?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"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
其中,driver路径查询:
cj中的jdbc中的Driver:(选择复制Copy Reference)
第三步 映射文件
创建接口-用创建class来创建 并放在资源文件中
注意编译后的(target文件中)文件内容要跟项目文件一致
当然,在编译项目时,maven在加载java没目录中的内容,xml不能正常更新需在pom.xml中添加如下配置
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources>
如果出现以下问题,有可能是因为没有设置主键,或者主键并没有自增
Incorrect integer value: 'TY' for column 'u_name' at row 1
更新操作
为什么执行加操作为什么没有数值,将下面的语句中设为true,否者一直是在内存中进行,并未持久化
SqlSession session=sqlSessionFactory.openSession(true);
传参问题
一个参数时候,映射文件中
多个参数中要的是arg1、arg2等等 但给的是uid,uname所以报错
解决方法 注意不能直接传参
1.将参数封装成map(按照框架要求进行传参)
<insert id="addUser2"> /*添加*/ insert into user1(uid,uname) values(#{arg0},#{arg1}) </insert>
2.将参数封装成map或者pojo
//先map并传入数值 Map map=new HashMap(); map.put("uid",4); map.put("uname","LTY"); testMapper.addUser2(map); //这里将map传参
//将TestMapper形参的值跟map一致 <insert id="addUser2"> /*添加*/ insert into user1(uid,uname) values(#{uid},#{uname}) </insert>
public static void testMap() throws IOException{ /*String resource = "mybatis-config.xml"; mybatis-config是一个资源文件,就可以实现自动追踪 org.apache.ibatis.io.Resources包中对应有获取动态地址的函数 InputStream inputStream = Resources.getResourceAsStream(resource); 会话工厂 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 会话,执行更新操作时候,需设为true,执行持久化操作 SqlSession session=sqlSessionFactory.openSession(true); TestMapper testMapper=session.getMapper(TestMapper.class); //先map并传入数值 Map map=new HashMap(); map.put("uid",4); map.put("uname","LTY"); testMapper.addUser2(map); //testMapper.addUser2(2,"JKF"); List<Map> list=testMapper.selectUser(); System.out.println(list);*/ } public static void testPojo() throws IOException{ String resource = "mybatis-config.xml"; /*mybatis-config是一个资源文件,就可以实现自动追踪*/ /*org.apache.ibatis.io.Resources包中对应有获取动态地址的函数*/ InputStream inputStream = Resources.getResourceAsStream(resource); /*会话工厂*/ SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); /*会话,执行更新操作时候,需设为true,执行持久化操作*/ SqlSession session=sqlSessionFactory.openSession(true); TestMapper testMapper=session.getMapper(TestMapper.class); //先map并传入数值 User user=new User(); user.setUid(5); user.setUname("王五"); testMapper.addUser2(user); //testMapper.addUser2(2,"JKF"); List<Map> list=testMapper.selectUser(); System.out.println(list); }
注意:映射文件中参数名字必须和map的key或是pojo的属性名保持一致
3.使用注释 使用@Param
这样传参就可以直接用uid和uname (在TestMapper.java文件中)
public void addUser3(@Param("uid") Integer uid,@Param("uname") String uname);
回参
对于增删改操作,在映射文件中没有对应的属性,在接口中增删改操作可以不接受返回值(void),也可以接收受影响行数(int),也可以接受更新操作是否成功(boolean)
对于查询而言必定有返回值,所以TestMapper.xml中select标签中的resultType元素必不可少
对于查询而言result必须要
1.返回值可以是基本类型/包装类
<select id="getCount" resultType="int"> select count(*) from user1 </select>
2.必须是实体类的全类名
但是可以简化
配置实体类别名,可以将整个包配置进来(默认别名就是当前类的类名,一般遵循首字母大写),也可以一个一个配置
<typeAliases> <package name="com.aaa.pojo"/> </typeAliases>
<typeAliases> <typeAlias alias="Author" type="domain.blog.Author"/> <typeAlias alias="Blog" type="domain.blog.Blog"/> <typeAlias alias="Comment" type="domain.blog.Comment"/> <typeAlias alias="Post" type="domain.blog.Post"/> <typeAlias alias="Section" type="domain.blog.Section"/> <typeAlias alias="Tag" type="domain.blog.Tag"/> </typeAliases>
3.返回一个list集合,在resultType中写的集合中的每一项,而不是这个集合
例 返回时List<pojo>,resultType中写的就是pojo,而不是list
<select id="selectUser" resultType="User"> /*这里是查询所以必定有返回值类型resultType*/ select * from user1 /*返回一个集合map*/ </select>
动态sql
-
if 条件判断
-
sql语句中多条件则用and并列(不是&&)
-
where标签会将and去掉
-
choose when otherwise:条件判断 类似java中if-else
where代替了sql中的where,当有限制条件时候,则自动加上where关键字,没有不加
set代替了update的set关键字
foreach:循环 collection:遍历的集合 item:集合的项 separator分隔符 open close
Spring
2.1 介绍
一个控制反转(IOC)和面向切面(AOP)的容器框架
目的:简化开发
spring的7个模块
2.2 控制反转(IOC)
在传统开发中,控制层依赖业务层,业务层依赖持久层,意味着需要在控制层实例化(new)业务层,业务成中需要实例化(new)持久层,但有了Spring容器后,就将依赖对象的创建和维护交给了容器,将对象的控制权交给了容器,实现了依赖对象间的解耦降低了对象间的耦合度。
2.3 入门案例
第一步 添加依赖
1.core,beans,content,expression(都是从网上直接粘过来的)
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.20</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.20</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.3.18</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.3.20</version> </dependency>
第三步 实例化容器
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
2.4 依赖注入(三种)
-
设置注入
第一步 在testService在提供依赖对象的set方法
private TestDao testDao; public void setTestDao(TestDao testDao){ this.testDao=testDao; } @Override public List<User> seleUser(Integer uid,String uname) { testDao.select(); return null; }
第二步 在spring.xml中建立依赖关系
测试
package com.aaa.test; import com.aaa.service.TestService; import com.aaa.service.imp.TestServicelmpl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSpring { public static void main(String[] args) { /*TestService testService=new TestServicelmpl(); testService.seleUser(null,null);*/ // create and configure beans ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); TestService testService=context.getBean("testService",TestService.class); testService.seleUser(null,null); } }
-
构造注入
第一步 在service中添加构造方法,依赖对象作为参数
private TestDao testDao; public void setTestDao(TestDao testDao){ this.testDao=testDao; } @Override public List<User> seleUser(Integer uid,String uname) { testDao.select(); return null; }
第二步 在spring.xml建立依赖关系
-
自动注入
第一步 和设置注入相同
第二步
<bean id="testService" class="com.aaa.service.imp.TestServiceImpl" autowire="byType"> <!-- collaborators and configuration for this bean go here --> <!--<property name="testDao" ref="testDao"></property> --> <!--告诉容器spring Dao是Service的一个属性--> <!--<constructor-arg name="testDao" ref="testDao"></constructor-arg>--> <!--第二种的第二步--> </bean>
2.5 注解
第一步 引入注释空间
第二步 添加注解扫描
<context:component-scan base-package="com.aaa"></context:component-scan>
第三步 添加注解
@Compoent @Controller @Service @Repository
这四个都是将类纳入Spring管理,但是为了更好的区分三层架构:
@Compoent @Controller是控制层 @Service是业务层 @Repository是持久层
强调注释作用在具体类上,而不是接口上
@Autowired 将依赖对象注入进来
AOP注入 因为和实际业务无关,则略(自学 先看java代理模式)
springMVC
4.1介绍
可以跟spring无缝衔接,典型web端的mvc框架,是一个纯正的servicelet系统
4.2核心组件
1.前段控制器 接受请求,返回响应
2.处理器、映射器 根据URL查找符合要求的handler
3.处理器、适配器 调用合适的handler(controller)
4.试图解析器 通过提逻辑视图名找到对应的物理试图(系统)
SSM整合
5.1添加依赖
从连接上数据库开始到结束,成为一次会话
-
添加spring和mybatis的整合依赖和dbcp的数据源
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.7.0</version> </dependency>
-
整合
spring-mybatis
<?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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--引入数据源--> <context:property-placeholder location="classpath:data.properties"></context:property-placeholder> <!--配置dbcp c3p0 JNDI--> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="${mysql.driver}"></property> <property name="url" value="${mysql.url}"></property> <property name="username" value="${mysql.username}"></property> <property name="password" value="${mysql.password}"></property> </bean> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--将mybatis交个spring管理--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!--映射器--> <!--mapper的扫描器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sessionFactory"></property> <property name="basePackage" value="com.aaa.mapper"></property> </bean> </beans>
mybatis-config.xml
<?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"> <configuration> <typeAliases> <package name="com.aaa.pojo"/> </typeAliases> <!-- <environments default="development"> <!– 配置的环境 注意是s说明可以配置多个环境–> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <!–驱动名–> <property name="url" value="jdbc:mysql:///student?serverTimezone = GMT"/> <!–这里是数据库名路径–> <property name="username" value="root"/> <!–连接名–> <property name="password" value="123456"/> <!–密码–> </dataSource> </environment> </environments> --> <!--映射器--> <!-- <mappers> <mapper resource="com/aaa/mapper/TestMapper.xml"/> </mappers> --> </configuration>
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>