CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
封装数据库的JavaBean:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookId;
private String bookName;
private int bookCounts;
private String detail;
}
编写持久层(dao层)代码:
public interface BookMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int BookId);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int BookId);
//查询全部的书
List<Books> queryAllBook();
}
编写业务层(service层)代码:
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int bookId);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int bookId);
//查询全部的书
List<Books> queryAllBook();
}
编写业务层实现类:
public class BookServiceImpl implements BookService {
public int addBook(Books books) {
return 0;
}
public int deleteBookById(int BookId) {
return 0;
}
public int updateBook(Books books) {
return 0;
}
public Books queryBookById(int bookId) {
return null;
}
public List<Books> queryAllBook() {
System.out.println("业务层查询书。。。");
return null;
}
}
编写表现层:
@Controller
public class BookController {
}
<!--开启注解扫描-->
<context:component-scan base-package="com.hh">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
在在业务层实现类上加上注解,将其交给IOC容器管理:
@Service("bookService")
public class BookServiceImpl implements BookService {}
测试Spring框架:
public class TestSpring {
@Test
public void test1(){
//加载配置文件
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
//获取对象
BookService bookService =
context.getBean("bookService", BookService.class);
//调用方法
bookService.queryAllBook();
}
}
编写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">
<!--DispatcherServlet-->
<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:sprignmvc.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>/*
编写springmvc.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
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.hh">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
beans>
编写前端页面:
<a href="allBook">查询所有图书</a>
编写表现层控制器类:
@Controller
public class BookController {
@RequestMapping("/allBook")
public String test(){
System.out.println("表现层查询所有图书");
return "allBook";
}
}
编写跳转页面:
<h3>查询所有图书</h3>
Spring整合SpringMvc需要在启动Tomcat服务器的时候就加载Spring的配置文件
在web.xml中配置监听器,目的是服务器启动的时候能够找到Spring的配置文件。
<!--配置监听器,默认加载WE-INF目录下的applicationContext.xml-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--设置配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
在表现层去调用业务层的方法:
@Controller
public class BookController {
@Autowired
BookService bookService;
@RequestMapping("/allBook")
public String test(){
System.out.println("表现层查询所有图书");
//表现层调用业务层的方法
bookService.queryAllBook();
return "allBook";
}
}
编写全局配置文件: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.hh.bean"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="username" value="root"/>
<property name="password" value="123"/>
<property name="url" value="jdbc:mysql:///ssmbuild"/>
<property name="driver" value="com.mysql.jdbc.Driver"/>
</dataSource>
</environment>
</environments>
</configuration>
编写映射配置文件:BookMapper.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">
<mapper namespace="com.hh.dao.BookMapper">
<insert id="addBook">
insert into ssmbuild.books(bookName, bookCounts, detail)
values(#{bookName},#{bookCounts},#{detail})
</insert>
<delete id="deleteBookById">
delete from ssmbuild.books where id=#{bookId}
</delete>
<update id="updateBook">
update ssmbuild.books
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where id=#{bookId}
</update>
<select id="queryBookById" resultType="books">
select * from ssmbuild.books where bookID=#{bookId}
</select>
<select id="queryAllBook" resultType="books">
select * from ssmbuild.books
</select>
</mapper>
将映射配置文件注册如全局配置文件中:
<mappers>
<mapper resource="com/hh/dao/BookMapper.xml"/>
</mappers>
测试类:
public class TestMyBatis {
@Test
public void test() throws IOException {
//加载配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
BookMapper mapper = sqlSession.getMapper(BookMapper.class);
List<Books> books = mapper.queryAllBook();
for(Books book:books)
{
System.out.println(book);
}
sqlSession.close();
inputStream.close();
}
}
在Spring的配置文件application.xml中配置Spring整合MyBatis的内容:
<!--配置数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"/>
<property name="password" value="123"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///ssmbuild"/>
</bean>
<!--配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--配置mybatis-config的文件位置-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--p配置dao接口的扫描包,动态实现了dao接口可以交给Spring容器管理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的包-->
<property name="basePackage" value="com.hh.dao"/>
</bean>
这样配置以后,那么mybatis-config.xml就可以变成下面这样了:
<configuration>
<typeAliases>
<package name="com.hh.bean"/>
</typeAliases>
<mappers>
<mapper resource="com/hh/dao/BookMapper.xml"/>
</mappers>
</configuration>
用业务层去调用持久层的方法:
先给持久层类加上dao注解,加上有就会交给IOC容器管理:
@Repository
public interface BookMapper {}
@Service("bookService")
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBookById(int bookId) {
return bookMapper.deleteBookById(bookId);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookById(int bookId) {
return bookMapper.queryBookById(bookId);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
重新修改表现层调用持久层的方法,让其查询的数据保存在域中,以便取出
查询所有图书:
@Controller
public class BookController {
@Autowired
BookService bookService;
@RequestMapping("/allBook")
public String test(Model model){
System.out.println("表现层查询所有图书");
//表现层调用业务层的方法
List<Books> books = bookService.queryAllBook();
model.addAttribute("books",books);
return "allBook";
}
}
编写跳转页面,从域中获取查询信息
<h3>所有图书为:</h3>
${books}
添加书籍:
在表现层调用业务层的添加书籍的方法,染回跳转到添加书籍页面:
//添加书籍
@RequestMapping("/addBook")
public String test(Books books){
bookService.addBook(books);
return "addBook";
}
删除书籍:
//删除书籍
@RequestMapping("/deleteBook")
public String test(int bookId){
bookService.deleteBookById(bookId);
return "deleteBook";
}
…