花了許多時間,初步完成了mybatis + spring的整合,準備工作如下;
使用版本: Spring 4.0.2 RELEASE、Mybatis 3.2.6、Sql Server jdbc 4.0、mybatis-spring 1.2.2
一、新創一個maven webapp project,這裡取名為MybatisDemo,package設定為com.test.mybatis,記得Archetype要設定webapp如下;
完成之後還要記得更改java compiler改成現在用的版本,build path 的 system library也要修改。
接著便修改pom.xml,這裡除了引用spring、mybatis以及spring-mybatis的相關jar檔案之外,還要有javaee-api、sql server驅動程式等等,詳細如下;
<properties>
<!-- spring版本號 -->
<spring.version>4.0.2.RELEASE</spring.version>
<!-- mybatis版本號 -->
<mybatis.version>3.2.6</mybatis.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- spring核心 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis/spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- sql server jdbc -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
<scope>system<scope/>
<systemPath>${basedir}/scr/main/webapp/WEB-INF/lib/sqljdbc4.jar</systemPath>
</dependency>
要注意的是,因為SQL Server的jdbc似乎與maven有認證方面的問題,所以設定方式有點不太一樣,要先下載該檔案並於console安裝,才能提供給maven使用,由於我們在eclipse中開發,因此直接將檔案放入專案中如下;
在以下的連結下載Sql Server jdbc Driver:
https://msdn.microsoft.com/en-us/sqlserver/aa937724
這裡使用4.0版,下載完解壓縮,接著將jdbc4.jar複製到專案底下WEB-INF/lib底下,dependency設定systemPath要設定絕對路徑,所以加上${basedir},這樣就設定完成了。
(也可以直接使用jtds的開源版jdbc驅動程式來連接SQL Server,如此一來直接在pom.xml定義下載即可)
二、使用mybatis generator產生我們所需要的model、mapper等檔案
先創立一個測試用Table接著新增些測試用資料,資料表結構如下;
use student
create table student_info
(
student_id bigint,
student_email varchar(200),
student_name varchar(50),
PRIMARY KEY(student_id)
)
接著創建一些package,主要是model、dao及mapping,接著準備使用MyBatis Generator產生資料
MyBatis Generator可從eclipse -> help -> install new software下載,網址如下;
http://mybatis.googlecode.com/svn/sub-projects/generator/trunk/eclipse/UpdateSite/
安裝完成之後,在專案的generatorConfig.xml上按右鍵,會出現Generate mybatis選項如下圖,點擊便可產生程式碼;
接著於專案根目錄底下新增一個generatorConfig.xml,內容如下;
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration >
<classPathEntry location="D:/eclipse_Luna/luna_workplace/MybatisDemo/MybatisDemo/src/main/webapp/WEB-INF/lib/sqljdbc4.jar" />
<context id="context1" >
<!-- 可更換自動生成的Example類別的名稱 -->
<plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
<property name="searchString" value="Example$" />
<property name="replaceString" value="Criteria" />
</plugin>
<!-- 生成的程式碼是否有註解 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<jdbcConnection driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver"
connectionURL="jdbc:sqlserver://localhost:1433;databaseName=student"
userId="studentadmin" password="test1234" />
<javaModelGenerator targetPackage="com.test.mybatis.model" targetProject="Mybatis" />
<sqlMapGenerator targetPackage="com.test.mybatis.mapper" targetProject="Mybatis" />
<javaClientGenerator targetPackage="com.test.mybatis.dao" targetProject="Mybatis" type="XMLMAPPER" />
<table tableName="student_info" >
</table>
</context>
</generatorConfiguration>
設定完成後,在該xml檔案上按右鍵,可以看到Generate mybatis的選項,選擇後便會自動幫我們產生需要的檔案,
這時候我們的專案架構如下;
這邊可依照需求將StudentInfoMapper.java改成StudentInfoDao.java以方便辨識管理。
三、設定介面與實作的Java類別、設定Spring與Mybatis
新增兩個package,service與service.impl,在其中新增介面接口與實作的 java class,我們先在其中新增用主鍵來尋找學生的方法如下;
StudentInfoService
package com.test.mybatis.student.service;
import com.test.mybatis.student.model.StudentInfo;
public interface StudentInfoService {
public StudentInfo getStudentInfoById(long student_Id);
}
StudentInfoServiceImpl
package com.test.mybatis.student.service.impl;
import com.test.mybatis.student.dao.StudentInfoDao;
import com.test.mybatis.student.model.StudentInfo;
import com.test.mybatis.student.service.StudentInfoService;
import org.springframework.stereotype.Service;
@Service("studentInfoService") //宣告一個Service Bean,如此就不需在spring-config.xml定義了
public class StudentInfoServiceImpl implements StudentInfoService{
private StudentInfoDao studentDao;
@Override
public StudentInfo getStudentInfoById(long student_Id) {
// TODO Auto-generated method stub
StudentInfo info = studentDao.selectByPrimaryKey(student_Id);
return info;
}
}
接著在專案/resource底下新增jdbc.properties備用;
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=student
dbusername=帳號
dbpassword=密碼
下一步也在resource底下新增一個mybatis-config.xml,這個文件可以幫我們將model class跟mybatis產生的mapper做mapping,內容如下;
<?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><!-- 這個標籤用來與指定的model class做mapping -->
<typeAlias type="com.test.mybatis.student.model.StudentInfo" alias="StudentInfo"/>
</typeAliases>
<mappers>
<mapper resource="com/test/mybatis/student/mapping/StudentInfoMapper.xml"/> <!-- mapper.xml所在位置 -->
</mappers>
</configuration>
接下來便是spring-config.xml的設定了,同樣在resource底下新增該檔案;
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- 這邊會去掃package底下用@號宣告的bean service -->
<context:component-scan base-package="com.test.mybatis.student" />
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 資料庫連線設定 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${dbusername}" />
<property name="password" value="${dbpassword}" />
</bean>
<!-- transaction manager, 資料庫交易處理程式 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- mybatis-spring使用sqlSessionFactory來操作資料庫 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 指定我們的設定檔 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- mapper對應的bean -->
<bean id="StudentInfoDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.test.mybatis.student.dao.StudentInfoDao" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>
以上設定完成之後,我們可以測試看看前面新增的method能不能使用,新增一個Action class;
StudentAction.java:
package com.test.mybatis.student.action;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.test.mybatis.student.model.StudentInfo;
import com.test.mybatis.student.service.StudentInfoService;
@WebServlet("/studentAction")
public class StudentAction extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long studentId = Long.parseLong(request.getParameter("studentId"));
//使用spring方式取得對應的method
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
StudentInfoService studentInfo = (StudentInfoService) context.getBean("studentInfoService");
StudentInfo info = studentInfo.getStudentInfoById(studentId); //使用impl內的Id取值方法
_log.info(info.getStudentName());
request.setAttribute("name", info.getStudentName());
ServletContext curContext = this.getServletContext();
RequestDispatcher dispatcher = curContext.getRequestDispatcher("/success.jsp");
dispatcher.forward(request, response); //傳回前端頁面
}
private static final Logger _log = Logger.getLogger(StudentAction.class.getName());
}
然後我們寫兩個測試用的前端jsp頁面,輸入studentId,將得到的學生姓名傳回;
順利傳回學生姓名,基本的spring + mybatis框架整合便完成了。
留言列表