1. 程式人生 > >Spring5整合MyBatis3

Spring5整合MyBatis3

Spring5整合MyBatis3

這是原始碼地址:https://download.csdn.net/download/qq_41900081/10785290

先說一下整合過程中解決比較久的低階問題:

1.applicationContext.xml檔名寫錯

2.db.properties中內容寫錯,比如寫成driver,url,username....正確為driverClass,jdbcUrl,user....

專案結構:

user表

book表

1.完成配置檔案

  db.properties

dataSource.driverClass=com.mysql.cj.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&amp&serverTimezone=UTC
dataSource.user=root
dataSource.password=root
dataSource.maxPoolSize=20
dataSource.maxIdleTime = 1000
dataSource.minPoolSize=6
dataSource.initialPoolSize=5

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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
			            http://www.springframework.org/schema/mvc/spring-mvc.xsd
			            http://www.springframework.org/schema/tx
			            http://www.springframework.org/schema/tx/spring-tx.xsd
			            http://mybatis.org/schema/mybatis-spring 
			            http://mybatis.org/schema/mybatis-spring.xsd ">
			      
	 <!-- mybatis:scan會將com.mapper包裡的所有介面當作mapper配置,之後可以自動引入mapper類-->  
    <mybatis:scan base-package="com.mapper"/>   
       
	 <!-- 掃描com包下面的java檔案,有Spring的相關注解的類,則把這些類註冊為Spring的bean -->
    <context:component-scan base-package="com"/>
    
	<!-- 使用PropertyOverrideConfigurer後處理器載入資料來源引數 -->
	<context:property-override location="classpath:db.properties"/>

	<!-- 配置c3p0資料來源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"/>
	
	<!-- 配置SqlSessionFactory,org.mybatis.spring.SqlSessionFactoryBean是Mybatis社群開發用於整合Spring的bean -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
	    p:dataSource-ref="dataSource"/>
	
	<!-- JDBC事務管理器 -->
	<bean id="transactionManager" 
	class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
		 p:dataSource-ref="dataSource"/>
	
	<!-- 啟用支援annotation註解方式事務管理 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
</beans>

springmvc-config.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd     
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
    <!-- 自動掃描該包,SpringMVC會將包下用了@controller註解的類註冊為Spring的controller -->
    <context:component-scan base-package="com.controller"/>
    <!-- 設定預設配置方案 -->
    <mvc:annotation-driven/>
    <!-- 使用預設的Servlet來響應靜態檔案 -->
    <mvc:default-servlet-handler/>
   <!-- 檢視解析器  p:prefix屬性表示字首  p:suffix 表示字尾  -->
     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/> 
    
</beans>

 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
	http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
	id="WebApp_ID" version="3.1">
	
	<!-- 配置spring核心監聽器,預設會以 /WEB-INF/applicationContext.xml作為配置檔案 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- contextConfigLocation引數用來指定Spring的配置檔案 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext*.xml</param-value>
	</context-param>
	
	<!-- 定義Spring MVC的前端控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <!-- 讓Spring MVC的前端控制器攔截所有請求 -->
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 編碼過濾器 -->
  <filter>
		<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
</web-app>

 2.持久層功能實現

(兩個普通的 javabean,寫上幾個屬性和get/set方法)

User.java

package com.domain;

import java.io.Serializable;

public class User implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String loginname;
	private String password;
	private String username;
	private String phone;
	private String address;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public User() {
		super();
		
	}
	public User(Integer id, String loginname, String password, String username, String phone, String address) {
		super();
		this.id = id;
		this.loginname = loginname;
		this.password = password;
		this.username = username;
		this.phone = phone;
		this.address = address;
	}
	
	@Override
	public String toString() {
		return "User [id=" + id + ", loginname=" + loginname + ", password=" + password + ", username=" + username
				+ ", phone=" + phone + ", address=" + address + "]";
	}
}

Book.java

package com.domain;

import java.io.Serializable;
import java.util.Date;

public class Book implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
	private String author;
	private String publication; //出版社
	private Date publicationdate;//出版日期
	private Double price;
	private String image;
	private String remark;//描述
	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 getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getPublication() {
		return publication;
	}
	public void setPublication(String publication) {
		this.publication = publication;
	}
	public Date getPublicationdate() {
		return publicationdate;
	}
	public void setPublicationdate(Date publicationdate) {
		this.publicationdate = publicationdate;
	}
	public Double getPrice() {
		return price;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	public String getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public Book() {
		super();
		
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", author=" + author + ", publication=" + publication
				+ ", publicationdate=" + publicationdate + ", price=" + price + ", image=" + image + ", remark="
				+ remark + "]";
	}
	public Book(Integer id, String name, String author, String publication, Date publicationdate, Double price,
			String image, String remark) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.publication = publication;
		this.publicationdate = publicationdate;
		this.price = price;
		this.image = image;
		this.remark = remark;
	}
	
}

BookMapper.java

package com.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.domain.Book;

/**
 * BookMapper介面
 * */
public interface BookMapper {

	/**
	 * 查詢所有圖書
	 * @return 圖書物件集合
	 * */
	@Select(" select * from book ")
	List<Book> findAll();
	
}

UserMapper.java

package com.mapper;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.domain.User;

/**
 * UserMapper介面
 * */
public interface UserMapper {
	
	/**
	 * 根據登入名和密碼查詢使用者
	 * @param String loginname
	 * @param String password
	 * @return 找到返回User物件,沒有找到返回null
	 * */
	@Select("select * from user where loginname = #{loginname} and password = #{password}")
	User findWithLoginnameAndPassword(@Param("loginname")String loginname,
			@Param("password") String password);

}

3.服務層功能的實現

 BookService.java

package com.service;

import java.util.List;

import com.domain.Book;

public interface BookService {
	List<Book> getAll();
}

UserService.java

package com.service;

import com.domain.User;

public interface UserService {
	User login(String loginname, String password);
}

BookServiceImpl.java

package com.service.impl;

import java.util.List;
import com.domain.Book;
import com.mapper.BookMapper;
import com.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)
@Service("bookService")

public class BookServiceImpl implements BookService{
	//自動注入BookMapper
	@Autowired
	private BookMapper bookMapper;
	@Transactional(readOnly=true)
	@Override
	public List<Book> getAll() {
		
		return bookMapper.findAll();
	}
	
}

UserSericeImpl.java

package com.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.domain.User;
import com.mapper.UserMapper;
import com.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService{
	//自動注入UserMapper 
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public User login(String loginname, String password) {
		return userMapper.findWithLoginnameAndPassword(loginname, password);
	}

}

4.控制層功能實現

FormController.java

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FormController {
	@RequestMapping("/login")
	public String login() {
		return "login";
	}
}

BookConroller.java

package com.controller;

import java.util.List;
import com.domain.Book;
import com.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;

/**
 * 處理圖書請求控制器
 * */
@Controller
public class BookController {
	
	/**
	 * 自動注入BookService
	 * */
	@Autowired
	@Qualifier("bookService")
	private BookService bookService;

	/**
	 * 處理/main請求
	 * */
	@RequestMapping(value="/main")
	 public String main(Model model){
		// 獲得所有圖書集合
		List<Book> book_list = bookService.getAll();
		// 將圖書集合新增到model當中
		model.addAttribute("book_list", book_list);
		// 跳轉到main頁面
		return "main";
	}
	
}

UserController.java

package com.controller;

import javax.servlet.http.HttpSession;
import com.domain.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

/**
 * 處理使用者請求控制器
 * */
@Controller
public class UserController {
	
	/**
	 * 自動注入UserService
	 * */
	@Autowired
	@Qualifier("userService")
	private UserService userService;

	/**
	 * 處理/login請求
	 * */
	@PostMapping(value="/login")
	 public ModelAndView login(
			 String loginname,String password,
			 ModelAndView mv,
			 HttpSession session){
		// 根據登入名和密碼查詢使用者,判斷使用者登入
		User user = userService.login(loginname, password);
		if(user != null){
			// 登入成功,將user物件設定到HttpSession作用範圍域
			session.setAttribute("user", user);
			// 轉發到main請求
			mv.setView(new RedirectView("main"));
		}else{
			// 登入失敗,設定失敗提示資訊,並跳轉到登入頁面
			mv.addObject("message", "登入名或密碼錯誤,請重新輸入!");
			mv.setViewName("login");
		}
		return mv;
	}
	
	
}

5.jsp頁面

login.jsp

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>登入</title>
</head>
<body>
<h3>登入頁面</h3>
<form action="login" method="post">
	<font color="red">${requestScope.message}</font>
	<table>
		<tr>
			<td>登入名:</td>
			<td><input type="text" id="loginname" name="loginname"></input></td>
		</tr>
		
		<tr>
			<td>密碼:</td>
			<td><input type="text" id="password" name="password"></input></td>
		</tr>
		
		<tr><td><input type="submit" value="登入"></input></td></tr>
	</table>
</form>

</body>
</html>

main.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<style type="text/css">
	table{border-collapse:collapse;border-spacing:0;border-left:1px solid #888;border-top:1px solid #888;background:#efefef;}
	th,td{border-right:1px solid #888;border-bottom:1px solid #888;padding:5px 15px;}
	th{font-weight:bold;background:#ccc;}
</style>
<title>首頁</title>
</head>
<body>
<h3>welcome ${sessionScope.user.username} login</h3>

<table border="1">
	<tr>
		<th>封面</th> <th>書名</th> <th>作者</th> <th>價格</th>
	</tr>
	<c:forEach items="${requestScope.book_list }" var="book">
		<tr>
			<td><img src="images/${book.image }" height="60" /></td>
			<td>${book.name }</td>
			<td>${book.author }</td>
			<td>${book.price}</td>
						
		</tr>
	</c:forEach>
</table>
</body>
</html>

部署專案之後測試:

登入成功:

登入失敗: