SpringMVC與MyBatis的整合
阿新 • • 發佈:2018-11-16
SpringMVC與MyBatis的整合
1、檔案結構圖
所有需要的JAR包都引入以後,首先進行Spring與MyBatis的整合,先看一個專案結構圖:
1.1、建立JDBC屬性檔案
jdbc.properities
1.2、log4j日誌系統(log4j.properities)jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://10.108.171.181:3306/mybatis?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=www1234 initialSize=0 maxIdle=20 minIdle=1
2、web.xml配置檔案# log4j configuration used during build and unit tests log4j.rootLogger=INFO,stdout log4j.threshhold=ALL log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} (%F:%M(%L)) - %m%n
3、applicationContext.xml<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Develop Example</display-name> <description>JSP 2.0 Tech Book's Examples</description> <icon> <small-icon>/images/small.gif</small-icon> <large-icon>/images/large.gif</large-icon> </icon> <!-- 首頁 --> <welcome-file-list> <welcome-file>/views/main.html</welcome-file> <welcome-file>main.htm</welcome-file> <welcome-file>main.jsp</welcome-file> </welcome-file-list> <!-- 錯誤頁 --> <error-page> <error-code>404</error-code> <location>/views/error.html</location> </error-page> <error-page> <error-code>500</error-code> <location>/rest/page/500</location> </error-page> <!-- 配置Spring配置檔案路徑 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <!-- 配置Spring上下文監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置log4j配置檔案路徑 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/mybatis/log4j.properties</param-value> </context-param> <!-- 配置Log4j監聽器 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- Spring MVC 核心控制器 DispatcherServlet 配置 --> <servlet> <servlet-name>index</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/index-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>index</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 解決post亂碼問題的過濾器 --> <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>
<?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"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
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://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 載入資料庫連線的資原始檔 -->
<context:property-placeholder location="/WEB-INF/mybatis/jdbc.properties"/>
<!-- 引入配置檔案 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/mybatis/jdbc.properties" />
</bean>
<!-- 配置資料來源 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${initialSize}"></property>
<property name="minIdle" value="${minIdle}"/>
<!-- 連線池最大空閒 -->
<property name="maxIdle" value="${maxIdle}"></property>
</bean>
<!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 資料庫連線池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 載入Mybatis全域性配置檔案 -->
<property name="configLocation" value="/WEB-INF/mybatis/mybatis-config.xml"/>
<!-- 自動掃描mapping.xml檔案 -->
<property name="mapperLocations" value="/WEB-INF/mybatis/mappers/*.xml" />
</bean>
<!-- 配置mybatis mapper介面 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.dao.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>
4、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>
<typeAlias type="com.dao.User" alias="User" />
</typeAliases>
</configuration>
5、usermapper.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.dao.UserMapper">
<select id="getUser" parameterType="int" resultType="User">
select * from users where id = #{id}
</select>
<insert id="insert" flushCache="true" parameterType="User">
insert into users (id, name, age) values (
#{id}, #{name}, #{age}
)
</insert>
<!-- 對應userDao中的updateUser方法 -->
<update id="update" parameterType="User">
update users set name = #{name}, age = #{age} where id = #{id};
</update>
<!-- 對應userDao中的deleteUser 方法 -->
<delete id="delete" parameterType="int">
delete from users where id = #{id};
</delete>
</mapper>
6、index-servet配置檔案
<?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:p="http://www.springframework.org/schema/p"
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
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自動掃描的包名 -->
<context:component-scan base-package="com.controller,com.dao" />
<!-- 預設的註解對映的支援 -->
<mvc:annotation-driven />
<!-- 檢視解釋類 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"/>
<property name="suffix" value=".html"/><!--可為空,方便實現自已的依據副檔名來選擇檢視解釋類的邏輯 -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
<mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>
<mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>
<mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>
<mvc:resources mapping="/views/**" location="/views/" cache-period="31556926"/>
</beans>
7、UserMapper.java
public interface UserMapper {
public User getUser(int id);
public void insert(User user);
public void update(User user);
public void delete(int id);
}
user.java
public class User {
private int id;
private String name;
private int age;
private int test;
public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public int getTest() {
return test;
}
public void setTest(int test) {
this.test = test;
}
}
8、UserService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService{
@Autowired
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User doGetUser(int id) {
return this.userMapper.getUser(id);
}
public void doInsertUser(User user) {
this.userMapper.insert(user);
}
public void doUpdateUser(User user) {
this.userMapper.update(user);
}
public void doDeleteUser(int id) {
this.userMapper.delete(id);
}
}
9、IndexController.java
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.dao.User;
import com.dao.UserService;
@Controller
public class IndexController {
@Autowired
private UserService userService;
private static Logger logger = Logger.getLogger(IndexController.class);
@RequestMapping({"/index","/"})
public String index() throws Exception{
User user1 = userService.doGetUser(7);
logger.info(user1.getName());
return "main";
}
}
10、測試顯示
訪問:http://localhost:8080/UI/index
從以上的顯示中可以發現,從資料庫中讀取了資料。