CREATE DATABASE `ssmbuild`; USE `ssmbuild`; CREATE TABLE `books` ( `bookID` INT(10) NOT NULL primary key, `bookName` VARCHAR(100) NOT NULL, `bookCounts` INT(11) NOT NULL , `detail` VARCHAR(200) NOT NULL ); INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES (1,'Java',1,'从入门到放弃'), (2,'MySQL',10,'从删库到跑路'), (3,'Linux',5,'从进门到进牢');
1、新建一Maven项目!
2、导入相关的pom依赖!
<!--依赖: junit 数据库驱动 连接池 servlet jsp mybatis mybatis-spring spring--> <dependencies> <!--Junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency> <!-- 数据库连接池 c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!--Servlet - JSP --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies> <!--静态资源导出问题--> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
(1)pojo 实体类层
(2)dao 数据层
(3)service 业务层
(4)controller 控制层
三大配置
1.mybatis-config的配置
-- typeAliases 起别名 在设置返回参数类型可以用当前类的类名
--mapper 映射我们实现dao接口的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> </configuration>
2.spring的配置
<?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"> </beans>
3.web.xml的配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> </web-app>
mybatis层
1.数据库配置文件database.properties
driver=com.mysql.cj.jdbc.Driver url =jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8 username=koko password=mxkmxk12567 #数据库配置文件
2.IDEA关联数据库 mysql
3.编写mybatis的核心配置文件
<?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> <!--别名,dao层方法的返回值可以为实体类的类名了--> <typeAliases> <package name="com.ma.pojo"/> </typeAliases> <!--mappers 映射dao接口的实现xml--> <mappers> <mapper resource="com/ma/dao/BookMapper.xml"/> </mappers> </configuration>
4.编写与数据库字段一一对应的实体类
懒人使用lombok插件! (快速实现属性、方法的编写)
package com.ma.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.web.bind.annotation.PathVariable; // 使用@Data注解可以快速实现类的属性和方法 (但没有有参函数) @Data // 使用@AllArgsConstructor 可以实现有参函数 (但无参函数被干掉了) @AllArgsConstructor // 使用@NoArgsConstructor 显示写入无参函数 @NoArgsConstructor public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; }
5、编写Dao层的 Mapper接口!
package com.ma.dao; import com.ma.pojo.Books; import java.util.List; public interface BookMapper { // 增加一本书 int addBook(Books books); // 删除一本书 int deleteBook(int id); // 更新一本书 int updateBook(Books books); // 查询一本书 Books queryBookById(int id); // 查询所有书 List<Books> queryBooks(); }
6、编写接口对应的 Mapper.xml 文件。需要导入MyBatis的包;
<?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="com.ma.dao.BookMapper"> <!--插入一条数据--> <insert id="addBook" parameterType="Books"> insert into ssmbuild.books (bookID, bookName, bookCounts, detail) values(#{bookID},#{bookName},#{bookCounts},#{detail}); </insert> <delete id="deleteBook" parameterType="int"> delete from ssmbuild.books where bookID = #{bookID} </delete> <update id="updateBook" parameterType="Books"> update ssmbuild.books set bookCounts = #{bookCounts} where bookID = #{bookID} </update> <select id="queryBookById" resultType="Books" parameterType="int"> select * from ssmbuild.books where bookID=#{bookID} </select> <select id="queryBooks" resultType="Books"> select * from ssmbuild.books </select> </mapper>
7、编写Service层的接口和实现类 (service主要调用dao层,所以service接口和dao层一样,主要通过在service 实现类中,通过set注入dao层,调用dao层的方法)
接口:
package com.ma.service; import com.ma.pojo.Books; import java.util.List; public interface BookService { // 增加一本书 int addBook(Books books); // 删除一本书 int deleteBook(int id); // 更新一本书 int updateBook(Books books); // 查询一本书 Books queryBookById(int id); // 查询所有书 List<Books> queryBooks(); }
实现类:
package com.ma.service; import com.ma.dao.BookMapper; import com.ma.pojo.Books; import java.util.List; public class BookServiceImpl implements BookService{ // 通过service去调用dao层 private BookMapper bookMapper; // set注入 public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public int addBook(Books books) { return bookMapper.addBook(books); } @Override public int deleteBook(int id) { return bookMapper.deleteBook(id); } @Override public int updateBook(Books books) { return bookMapper.updateBook(books); } @Override public Books queryBookById(int id) { return bookMapper.queryBookById(id); } @Override public List<Books> queryBooks() { return bookMapper.queryBooks(); } }
spring-dao层
我们通过spring去接管我们的mybatis层
我们在spring-dao层中做连接池,做sqlSessionFactory的工厂,把Dao接口注入到spring容器中
<?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"> <!--关联数据库配置文件--> <context:property-placeholder location="classpath:database.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driver}"/> <property name="jdbcUrl" value="${url}"/> <property name="user" value="${username}"/> <property name="password" value="${password}"/> <!-- c3p0连接池的私有属性 --> <property name="maxPoolSize" value="30"/> <property name="minPoolSize" value="10"/> <!-- 关闭连接后不自动commit --> <property name="autoCommitOnClose" value="false"/> <!-- 获取连接超时时间 --> <property name="checkoutTimeout" value="10000"/> <!-- 当获取连接失败重试次数 --> <property name="acquireRetryAttempts" value="2"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--注入数据库连接池--> <property name="dataSource" ref="dataSource"/> <!--配置mybatis的全局配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入sqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="com.ma.dao"/> </bean> </beans>
Spring-service层
<?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"> <!--1.扫描service下的包--> <context:component-scan base-package="com.ma.service"/> <!--2.将我们的所有业务类注入到spring,可通过配置,或者注解实现--> <bean id="BookServiceImpl" class="com.ma.service.BookServiceImpl"> <property name="bookMapper" ref="bookMapper"/> </bean> <!--3.声明式事务提交--> <bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--配置数据源--> <property name="dataSource" ref="dataSource"/> </bean> </beans>
SpringMVC层
----DispatcherServlet总体接管
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!--一定要注意:我们这里加载的是总的配置文件,之前被这里坑了!--> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--encodingFilter--> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--Session过期时间--> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app>
spring-web.xml
<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 http://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"> <!--映射器 适配器--> <mvc:annotation-driven/> <!--静态资源过滤 例如css js--> <mvc:default-servlet-handler/> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 4.扫描web相关的bean --> <context:component-scan base-package="com.ma.controller" /> </beans>
最后Controller层编写类
package com.ma.controller; import com.ma.pojo.Books; import com.ma.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Controller @RequestMapping("/books") public class BookController { // controller调service层 // 怎么调? 通过注解注入 @Autowired @Qualifier("BookServiceImpl") private BookService bookService; // 查询全部书籍,并且返回一个书籍展示页面 @RequestMapping("/allbook") private String list(Model model){ List<Books> books = bookService.queryBooks(); model.addAttribute("list",books); return "allbook"; } }
总结一下
1.spring-dao层主要操作数据库。 -怎么操作数据库? ---- 通过mybatis
2.spring-service层调用dao层。 -怎么调用dao层? ---- dao接口注入到spring service通过spring配置dao接口
3.spring-mvc 主要操作service层。
service怎么调用dao层:
spring-dao层最后的扫描dao层接口注入到spring容器中,是因为service层必须要调dao层,怎么调用dao层?就是通过set注入调用。在spring-service 把实现类注入到容器中,
通过配置,因为我们已经把dao层注入到spring容器当中了,我们可以通过ref引用获取dao层的接口赋值给service层set注入的dao,从而实现了service调用dao层
controller层怎么控制service层?
通过注解注入service与其原理和调用dao层一致