<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.0modelVersion>
<groupId>com.yuangroupId>
<artifactId>SSMartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<maven.compiler.source>17maven.compiler.source>
<maven.compiler.target>17maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.6version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.28version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.19version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.22version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.3.19version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
project>
二、mybatis层
1.创建实体类
package com.yuan.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Books {
private long bookID;
private String bookName;
private long bookCounts;
private String detail;
}
2.Dao层接口
public interface BookMapper {
//查询所有书籍
List<Books> queryAllBooks();
Books queryBooksById(@Param("id") long id);
int deleteBooksById(@Param("id") long id);
int updateBooksById(@Param("id") long id);
int insertBooks(Books books);
}
3.配置核心配置文件
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<typeAliases>
<package name="com.yuan.pojo"/>
typeAliases>
<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 class="com.yuan.mapper.BooksMapper"/>
mappers>
configuration>
4.接口绑定xml配置文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yuan.mapper.BooksMapper">
<select id="queryAllBooks" resultType="Books">
select * from books;
select>
<insert id="insertBooks" parameterType="Books">
insert into books(bookID, bookName, bookCounts, detail) values(#{bookID},#{bookName},#{bookCounts},#{detail})
insert>
<update id="updateBooksById" parameterType="books">
update books set bookID = #{bookID},bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail} where bookID = #{id};
update>
<delete id="deleteBooksById" >
delete from books where bookID = #{id};
delete>
mapper>
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssmbuild?autoReconnect=true&useUnicode=true&createDatabaseIfNotExist=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC
user=root
password=yuanxipeng6
5.测试运行
public class UserMapper_Test {
@Test
public void queryAllBooks() throws java.io.IOException
{
//获取SqlSession
String resource = "Mybatis-Config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlsessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlsessionFactory.openSession();
//查询所有的书籍
BooksMapper booksMapper = sqlSession.getMapper(BooksMapper.class);
List<Books> list = booksMapper.queryAllBooks();
//展示结果
for (Books book : list)
{
System.out.println(book);
}
}
}
三、spring层
1.spring整合mybatis层
1.1创建sqlsession
<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 http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.yuan.mapper"/>
<context:property-placeholder location="db.properties"/>
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
bean>
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSourceTransactionManager"/>
<property name="configLocation" value="Mybatis-Config.xml"/>
bean>
<bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSessionTemplate">
<constructor-arg ref="sqlSessionFactoryBean"/>
bean>
beans>
1.2 修改简化mybatis配置文件
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<typeAliases>
<package name="com.yuan.pojo"/>
typeAliases>
<mappers>
<mapper class="com.yuan.mapper.BooksMapper"/>
mappers>
configuration>
这里我们只保留mapper,setting和typealias
1.3 注入sqlSession实现类因为我们不能将mapper接口交给spring托管,也就是说接口不能创建实例,现在我们想要使用接口的方法,我们之好编写一个接口的实现类,然后重写它的方法,将sqlsession注入,完成具体的业务。同时这样也方便后面aop织入
@Repository//将这个类注册为bean
public class BooksMapperImpl implements BooksMapper{
@Autowired//实现自动装配
@Qualifier("sqlSessionTemplate")
private SqlSessionTemplate template;
@Override
public List<Books> queryAllBooks() {
BooksMapper booksMapper = template.getMapper(BooksMapper.class);
return booksMapper.queryAllBooks();
}
@Override
public Books queryBooksById(long id) {
return null;
}
@Override
public int deleteBooksById(long id) {
return 0;
}
@Override
public int updateBooksById(long id, Books books) {
return 0;
}
@Override
public int insertBooks(Books books) {
return 0;
}
}
1.4 测试
public class UserMapper_Test {
@Test
public void queryAllBooks()
{
//获取SqlSession
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
BooksMapper booksMapper = (BooksMapper) context.getBean("booksMapperImpl");
for (Books book : booksMapper.queryAllBooks()) {
System.out.println(book);
}
}
}
2.spring整合service层
2.1 Spring-Service.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"
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-4.0.xsd">
<context:component-scan base-package="com.yuan.service"/>
beans>
2.2 编写Service层的业务类
package com.yuan.service;
import com.yuan.mapper.BooksMapperImpl;
import com.yuan.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BooksServiceImpl implements BooksService{
@Autowired
@Qualifier("booksMapperImpl")
private BooksMapperImpl booksMapperImpl;
@Override
public List<Books> queryAllBooks() {
List<Books> list = booksMapperImpl.queryAllBooks();
return list;
}
@Override
public Books queryBooksById(long id) {
return null;
}
@Override
public int deleteBooksById(long id) {
return 0;
}
@Override
public int updateBooksById(long id, Books books) {
return 0;
}
@Override
public int insertBooks(Books books) {
return 0;
}
}
3.spring整合SpringMVC层
3.1 将项目类型改为WEB类型
3.2 注册DispatcherServlet因为我创建项目的时候是个普通的maven项目,所以需要改一下project struct(这里注意需要将需要的jar包导入到和class同一目录下面的lib目录里面)
<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>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:ApplicationContext.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
3.3 spring-MVC.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-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
<context:component-scan base-package="com.yuan.controller"/>
<mvc:annotation-driven/>
<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>
beans>
四、业务实现
现在框架搭好了我们该实现具体的业务了
这里我总共实现了五个功能分别是:
- 显示所有用户
- 添加一个用户
- 删除一个用户
- 更新一个用户
- 按照名字的模糊查询
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yuan.mapper.BooksMapper">
<select id="queryAllBooks" resultType="Books">
select * from books;
select>
<insert id="insertBooks" parameterType="Books">
insert into books(bookName, bookCounts, detail) values(#{bookName},#{bookCounts},#{detail})
insert>
<update id="updateBooksById" parameterType="books">
update books set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail} where bookID = #{bookID};
update>
<delete id="deleteBooksById" >
delete from books where bookID = #{id};
delete>
<select id="queryBooksById" resultType="books">
select * from books where bookID = #{id};
select>
<select id="queryBooksByName" resultType="books">
select * from books where bookName like concat('%',#{bookName},'%');
select>
mapper>
4.2 DAO层
public interface BooksMapper {
//查询所有书籍
List<Books> queryAllBooks();
Books queryBooksById(@Param("id") long id);
int deleteBooksById(@Param("id") long id);
int updateBooksById(Books books);
int insertBooks(Books books);
List<Books> queryBooksByName(String bookName);
}
@Repository
public class BooksMapperImpl implements BooksMapper{
@Autowired
@Qualifier("sqlSessionTemplate")
private SqlSessionTemplate template;
@Override
public List<Books> queryAllBooks() {
BooksMapper booksMapper = template.getMapper(BooksMapper.class);
return booksMapper.queryAllBooks();
}
@Override
public Books queryBooksById(long id) {
BooksMapper booksMapper= template.getMapper(BooksMapper.class);
Books rs = booksMapper.queryBooksById(id);
return rs;
}
@Override
public int deleteBooksById(long id) {
BooksMapper booksMapper = template.getMapper(BooksMapper.class);
int rs = booksMapper.deleteBooksById(id);
return rs;
}
@Override
public int updateBooksById( Books books) {
BooksMapper booksMapper = template.getMapper(BooksMapper.class);
int rs = booksMapper.updateBooksById(books);
return rs;
}
@Override
public int insertBooks(Books books) {
BooksMapper booksMapper = template.getMapper(BooksMapper.class);
int rs = booksMapper.insertBooks(books);
return rs;
}
@Override
public List<Books> queryBooksByName(String bookName) {
BooksMapper booksMapper = template.getMapper(BooksMapper.class);
List<Books> rs = booksMapper.queryBooksByName(bookName);
return rs;
}
}
这里我们也可以直接BooksServiceImpl 去继承DaoSoupport,从而避免了注入SqlSession
4.3 service层public interface BooksService {
List<Books> queryAllBooks();
Books queryBooksById( long id);
int deleteBooksById( long id);
int updateBooksById(Books books);
int insertBooks(Books books);
List<Books> queryBooksByName(String bookName);
}
@Service
public class BooksServiceImpl implements BooksService{
@Autowired
@Qualifier("booksMapperImpl")
private BooksMapperImpl booksMapperImpl;
@Override
public List<Books> queryAllBooks() {
List<Books> list = booksMapperImpl.queryAllBooks();
return list;
}
@Override
public Books queryBooksById(long id) {
Books rs = booksMapperImpl.queryBooksById(id);
return rs;
}
@Override
public int deleteBooksById(long id) {
int rs = booksMapperImpl.deleteBooksById(id);
return rs;
}
@Override
public int updateBooksById( Books books) {
int rs = booksMapperImpl.updateBooksById(books);
return rs;
}
@Override
public int insertBooks(Books books) {
int rs = booksMapperImpl.insertBooks(books);
return rs;
}
@Override
public List<Books> queryBooksByName(String bookName) {
List<Books> rs = booksMapperImpl.queryBooksByName(bookName);
return rs;
}
}
4.4 controller层
@Controller
@RequestMapping("/books")
public class MyController {
@Autowired
@Qualifier("booksServiceImpl")
private BooksServiceImpl booksServiceImpl;
@RequestMapping("/queryAllBooks")
public String queryAllBooks(Model model)
{
List<Books> list = booksServiceImpl.queryAllBooks();
model.addAttribute("list",list);
return "queryAllBooks";
}
@RequestMapping("/gotoInsertBook")
public String gotoInsertBook()
{
return "insertBook";
}
@RequestMapping("insertBook")
public String insertBook(Books book)
{
booksServiceImpl.insertBooks(book);
return "redirect:/books/queryAllBooks";
}
@RequestMapping("deleteBook")
public String deleteBook(long id)
{
booksServiceImpl.deleteBooksById(id);
return "redirect:/books/queryAllBooks";
}
@RequestMapping("gotoUpdateBook")
public String gotoUpdateBook(long id,Model model)
{
Books books = booksServiceImpl.queryBooksById(id);
model.addAttribute("book",books);
return "updateBook";
}
@RequestMapping("updateBook")
public String updateBook(Books book)
{
booksServiceImpl.updateBooksById(book);
return "redirect:/books/queryAllBooks";
}
@RequestMapping("queryBooksByName")
public String queryBooksByName(String bookName,Model model)
{
List<Books> list = null;
//这里我们不能直接bookName==null,这里传过来的对象始终不是null,只是内容始终是空!!!
if(bookName.equals(""))
{
model.addAttribute("msg","输入结果为空!");
}else
{
list = booksServiceImpl.queryBooksByName(bookName);
model.addAttribute("list",list);
}
return "queryAllBooks";
}
}
4.5 前端页面
主页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Title
书籍列表 —— 显示所有书籍
新增书籍
书籍编号
书籍名字
书籍数量
书籍详情
*** 作
${book.getBookID()}
${book.getBookName()}
${book.getBookCounts()}
${book.getDetail()}
更新
|
删除
添加书籍页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
新增书籍
新增书籍
更新书籍页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
新增书籍
更新书籍
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)