MyBatis簡介與配置MyBatis+Spring+MySql


1.1MyBatis簡介

      MyBatis 是一個可以自定義SQL、存儲過程和高級映射的持久層框架。MyBatis 摒除了大部分的JDBC代碼、手工設置參數和結果集重獲。MyBatis 只使用簡單的XML 和注解來配置和映射基本數據類型、Map 接口和POJO 到數據庫記錄。相對Hibernate和Apache OJB等“一站式”ORM解決方案而言,Mybatis 是一種“半自動化”的ORM實現。
需要使用的Jar包:mybatis-3.0.2.jar(mybatis核心包)。mybatis-spring-1.0.0.jar(與Spring結合包)。

下載地址:
http://ibatis.apache.org/tools/ibator
http://code.google.com/p/mybatis/

 

1.2MyBatis+Spring+MySql簡單配置

1.2.1搭建Spring環境

1,建立maven的web項目;
2,加入Spring框架、配置文件;
3,在pom.xml中加入所需要的jar包(spring框架的、mybatis、mybatis-spring、junit等);
4,更改web.xml和spring的配置文件;
5,添加一個jsp頁面和對應的Controller;
6,測試。

可參照:http://limingnihao.iteye.com/blog/830409使用Eclipse的Maven構建SpringMVC項目


1.2.2建立MySql數據庫

建立一個學生選課管理數據庫。
表:學生表、班級表、教師表、課程表、學生選課表。
邏輯關系:每個學生有一個班級;每個班級對應一個班主任教師;每個教師只能當一個班的班主任;

使用下面的sql進行建數據庫,先建立學生表,插入數據(2條以上)。

更多sql請下載項目源文件,在resource/sql中。

Sql代碼 

 

 收藏代碼

  1. /* 建立數據庫 */  
  2. CREATE DATABASE STUDENT_MANAGER;  
  3. USE STUDENT_MANAGER;  
  4.   
  5. /***** 建立student表 *****/  
  6. CREATE TABLE STUDENT_TBL  
  7. (  
  8.    STUDENT_ID         VARCHAR(255) PRIMARY KEY,  
  9.    STUDENT_NAME       VARCHAR(10) NOT NULL,  
  10.    STUDENT_SEX        VARCHAR(10),  
  11.    STUDENT_BIRTHDAY   DATE,  
  12.    CLASS_ID           VARCHAR(255)  
  13. );  
  14.   
  15. /*插入學生數據*/  
  16. INSERT INTO STUDENT_TBL (STUDENT_ID,  
  17.                          STUDENT_NAME,  
  18.                          STUDENT_SEX,  
  19.                          STUDENT_BIRTHDAY,  
  20.                          CLASS_ID)  
  21.   VALUES   (123456,  
  22.             '某某某',  
  23.             '女',  
  24.             '1980-08-01',  
  25.             121546  
  26.             )  

 


創建連接MySql使用的配置文件mysql.properties。

Mysql.properties代碼 

 

 收藏代碼

  1. jdbc.driverClassName=com.mysql.jdbc.Driver  
  2. jdbc.url=jdbc:mysql://localhost:3306/student_manager?user=root&password=limingnihao&useUnicode=true&characterEncoding=UTF-8  

 

 

1.2.3搭建MyBatis環境

順序隨便,現在的順序是因為可以盡量的少的修改寫好的文件。


1.2.3.1創建實體類: StudentEntity

Java代碼 

 

 收藏代碼

  1. public class StudentEntity implements Serializable {  
  2.   
  3.     private static final long serialVersionUID = 3096154202413606831L;  
  4.     private ClassEntity classEntity;  
  5.     private Date studentBirthday;  
  6.     private String studentID;  
  7.     private String studentName;  
  8.     private String studentSex;  
  9.       
  10.     public ClassEntity getClassEntity() {  
  11.         return classEntity;  
  12.     }  
  13.   
  14.     public Date getStudentBirthday() {  
  15.         return studentBirthday;  
  16.     }  
  17.   
  18.     public String getStudentID() {  
  19.         return studentID;  
  20.     }  
  21.   
  22.     public String getStudentName() {  
  23.         return studentName;  
  24.     }  
  25.   
  26.     public String getStudentSex() {  
  27.         return studentSex;  
  28.     }  
  29.   
  30.     public void setClassEntity(ClassEntity classEntity) {  
  31.         this.classEntity = classEntity;  
  32.     }  
  33.   
  34.     public void setStudentBirthday(Date studentBirthday) {  
  35.         this.studentBirthday = studentBirthday;  
  36.     }  
  37.   
  38.     public void setStudentID(String studentID) {  
  39.         this.studentID = studentID;  
  40.     }  
  41.   
  42.     public void setStudentName(String studentName) {  
  43.         this.studentName = studentName;  
  44.     }  
  45.   
  46.     public void setStudentSex(String studentSex) {  
  47.         this.studentSex = studentSex;  
  48.     }  
  49. }  

 

 

 

1.2.3.2創建數據訪問接口

Student類對應的dao接口:StudentMapper。

Java代碼 

 

 收藏代碼

  1. public interface StudentMapper {  
  2.       
  3.     public StudentEntity getStudent(String studentID);  
  4.       
  5.     public StudentEntity getStudentAndClass(String studentID);  
  6.       
  7.     public List<StudentEntity> getStudentAll();  
  8.       
  9.     public void insertStudent(StudentEntity entity);  
  10.       
  11.     public void deleteStudent(StudentEntity entity);  
  12.       
  13.     public void updateStudent(StudentEntity entity);  
  14. }  

 


1.2.3.3創建SQL映射語句文件


Student類的sql語句文件StudentMapper.xml
resultMap標簽:表字段與屬性的映射。
Select標簽:查詢sql。

Xml代碼 

 

 收藏代碼

  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="com.manager.data.StudentMapper">  
  4.   
  5.     <resultMap type="StudentEntity" id="studentResultMap">  
  6.         <id property="studentID" column="STUDENT_ID"/>  
  7.         <result property="studentName" column="STUDENT_NAME"/>  
  8.         <result property="studentSex" column="STUDENT_SEX"/>  
  9.         <result property="studentBirthday" column="STUDENT_BIRTHDAY"/>  
  10.     </resultMap>  
  11.       
  12.     <!-- 查詢學生,根據id -->  
  13.     <select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap">  
  14.         <![CDATA[ 
  15.             SELECT * from STUDENT_TBL ST 
  16.                 WHERE ST.STUDENT_ID = #{studentID}  
  17.         ]]>   
  18.     </select>  
  19.       
  20.     <!-- 查詢學生列表 -->  
  21.     <select id="getStudentAll"  resultType="com.manager.data.model.StudentEntity" resultMap="studentResultMap">  
  22.         <![CDATA[ 
  23.             SELECT * from STUDENT_TBL 
  24.         ]]>   
  25.     </select>  
  26.       
  27. </mapper>  

 

 


1.2.3.4創建MyBatis的mapper配置文件

在src/main/resource中創建MyBatis配置文件:mybatis-config.xml。
typeAliases標簽:給類起一個別名。com.manager.data.model.StudentEntity類,可以使用StudentEntity代替。
Mappers標簽:加載MyBatis中實體類的SQL映射語句文件。

 

Xml代碼 

 

 收藏代碼

  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  3. <configuration>  
  4.     <typeAliases>  
  5.         <typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity"/>  
  6.     </typeAliases>  
  7.     <mappers>  
  8.         <mapper resource="com/manager/data/maps/StudentMapper.xml" />  
  9.     </mappers>  
  10. </configuration>    

 

 

 


1.2.3.5修改Spring 的配置文件

主要是添加SqlSession的制作工廠類的bean:SqlSessionFactoryBean,(在mybatis.spring包中)。需要指定配置文件位置和dataSource。
和數據訪問接口對應的實現bean。通過MapperFactoryBean創建出來。需要執行接口類全稱和SqlSession工廠bean的引用。

Xml代碼 

 

 收藏代碼

  1. <!-- 導入屬性配置文件 -->  
  2. <context:property-placeholder location="classpath:mysql.properties" />  
  3.   
  4. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  5.     <property name="driverClassName" value="${jdbc.driverClassName}" />  
  6.     <property name="url" value="${jdbc.url}" />  
  7. </bean>  
  8.   
  9. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  10.     <property name="dataSource" ref="dataSource" />  
  11. </bean>  
  12.   
  13. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  14.     <property name="configLocation" value="classpath:mybatis-config.xml" />  
  15.     <property name="dataSource" ref="dataSource" />  
  16. </bean>  
  17.   
  18. <!— mapper bean -->  
  19. <bean id="studentMapper" class="org.mybatis.spring.MapperFactoryBean">  
  20.     <property name="mapperInterface" value="com.manager.data.StudentMapper" />  
  21.     <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
  22. </bean>  

 

 

也可以不定義mapper的bean,使用注解:

將StudentMapper加入注解

 

Java代碼 

 

 收藏代碼

  1. @Repository  
  2. @Transactional  
  3. public interface StudentMapper {  
  4. }  

 

 

對應的需要在dispatcher-servlet.xml中加入掃描:

 

Xml代碼 

 

 收藏代碼

  1. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  2.     <property name="annotationClass" value="org.springframework.stereotype.Repository"/>  
  3.     <property name="basePackage" value="com.liming.manager"/>  
  4.     <property name="sqlSessionFactory" ref="sqlSessionFactory"/>  
  5. </bean>  

 

 

 

1.2.4測試StudentMapper

使用SpringMVC測試,創建一個TestController,配置tomcat,訪問index.do頁面進行測試:

Java代碼 

 

 收藏代碼

  1. @Controller  
  2. public class TestController {  
  3.   
  4.     @Autowired  
  5.     private StudentMapper studentMapper;  
  6.       
  7.     @RequestMapping(value = "index.do")  
  8.     public void indexPage() {     
  9.         StudentEntity entity = studentMapper.getStudent("10000013");  
  10.         System.out.println("name:" + entity.getStudentName());  
  11.     }     
  12. }  

 

 

使用Junit測試:

Java代碼 

 

 收藏代碼

  1. 使用Junit測試:  
  2. Java代碼  
  3. @RunWith(value = SpringJUnit4ClassRunner.class)  
  4. @ContextConfiguration(value = "test-servlet.xml")  
  5. public class StudentMapperTest {  
  6.       
  7.     @Autowired  
  8.     private ClassMapper classMapper;  
  9.       
  10.     @Autowired  
  11.     private StudentMapper studentMapper;  
  12.       
  13.     @Transactional  
  14.     public void getStudentTest(){  
  15.         StudentEntity entity = studentMapper.getStudent("10000013");  
  16.         System.out.println("" + entity.getStudentID() + entity.getStudentName());  
  17.           
  18.         List<StudentEntity> studentList = studentMapper.getStudentAll();  
  19.         for( StudentEntity entityTemp : studentList){  
  20.             System.out.println(entityTemp.getStudentName());  
  21.         }  
  22.           
  23.     }  
  24. }  

 

 

MyBatis學習 之 一、MyBatis簡介與配置MyBatis+Spring+MySql

MyBatis學習 之 二、SQL語句映射文件(1)resultMap

MyBatis學習 之 二、SQL語句映射文件(2)增刪改查、參數、緩存

MyBatis學習 之 三、動態SQL語句

MyBatis學習 之 四、MyBatis配置文件

61 

11 

分享到:  

MyBatis學習 之 二、SQL語句映射文件(1 ... | SpringFlex框架搭建 之 二、配置使用Spri ...

參考知識庫

Java EE知識庫17380  關注 | 1301  收錄

評論

 

28 樓 saybar 2017-01-05  

哪里有源代碼啊,?能否發一份?還有就是 ClassEntity 是什么類?怎么不一樣啊?我郵箱:411038060@qq.com

27 樓 liangzulin 2016-12-05  

classentity是啥?哪個包的類啊?
這教程並不完整啊!

26 樓 di1984HIT 2014-10-22  

寫的很好啊~

25 樓 mojito515 2013-05-05  

引用


<bean id="studentMapper" class="org.mybatis.spring.MapperFactoryBean">  
    <property name="mapperInterface" value="com.manager.data.StudentMapper" />  
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />  



MapperFactoryBean的路徑寫錯了,應該是org.mybatis.spring.mapper.MapperFactoryBean

24 樓 大貓熊 2013-02-16  

你好,可以把源代碼發到343816974@qq.com郵箱好嗎?

23 樓 xvsfeo 2012-12-20  

你好,可以把源代碼發到410742933@qq.com郵箱好嗎?

22 樓 hdwmp123 2012-06-13  

附件哪里下載呢?

21 樓 phoenixsfans 2012-06-10  

您好,我也正在學MyBatis想看看您的上面例子的源碼,如果可以的話麻煩發到我郵箱 kissinglinux@gmail.com  謝謝

20 樓 hao_evolution 2012-04-10  

limingnihao 寫道

hao_evolution 寫道

為啥加兩次 @Transactional ,在service層加不就可以了?


你說的兩次,第二次指的是在junit里邊吧。在junit里面加@Transactional可以使在測試增刪改后進行數據回滾,保證數據和測試之前的一樣,不加也沒問題。
@Repository  
@Transactional  
public interface StudentMapper {  


個人覺得這里沒必要加事務,在service層去加事務控制

19 樓 limingnihao 2012-04-09  

hao_evolution 寫道

為啥加兩次 @Transactional ,在service層加不就可以了?


你說的兩次,第二次指的是在junit里邊吧。在junit里面加@Transactional可以使在測試增刪改后進行數據回滾,保證數據和測試之前的一樣,不加也沒問題。

18 樓 hao_evolution 2012-04-09  

為啥加兩次 @Transactional ,在service層加不就可以了?

17 樓 xiaoqiS 2012-02-20  

不錯的入門教程

16 樓 幸福人生 2011-07-25  

我的配置文件: 
<?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:tx="http://www.springframework.org/schema/tx" 
xsi:schemaLocation=" 
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 

<!-- Scans the classpath of this application for @Components to deploy as beans --> 
<context:component-scan base-package="com.myproject" /> 


<!-- 定義受環境影響易變的變量 --> 
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> 
<property name="ignoreResourceNotFound" value="true" /> 
<property name="locations"> 
<list> 
<!-- 本地開發環境配置 --> 
<value>classpath:jdbc.local.properties</value> 
<value>classpath:sys_config.properties</value> 

</list> 
</property> 
</bean> 


<!-- 數據源配置,使用應用內的DBCP數據庫連接池 --> 
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" lazy-init="false">
<property name="driverClassName" value="${jdbc.driverClassName}"/> 
<property name="url" value="${jdbc.url_mex}"/> 
<property name="username" value="${jdbc.username_mex}"/> 
<property name="password" value="${jdbc.password_mex}"/> 

<!-- Connection Pooling Info --> 
<property name="maxIdle" value="${dbcp.maxIdle}" /> 
<property name="maxActive" value="${dbcp.maxActive}" /> 
<property name="timeBetweenEvictionRunsMillis" value="3600000" /> 
<property name="minEvictableIdleTimeMillis" value="3600000" /> 
<property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}" /> 
</bean> 

<!-- 事務管理器配置,單數據源事務 --> 

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
    <property name="dataSource" ref="dataSource" />  
</bean>  
  
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
<property name="configLocation" value="classpath:ibatis-config.xml" /> 
<property name="dataSource" ref="dataSource" /> 
</bean> 



<!-- mapper bean -->  
<bean id="StudentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">  
    <property name="mapperInterface" value="com.myproject.report.dao.StudentMapper" />  
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
</bean> 


<bean name="stringHttpMessageConverter" 
class="org.springframework.http.converter.StringHttpMessageConverter"> 
<property name="supportedMediaTypes"> 
<list> 
<value>text/plain;charset=UTF-8</value> 
</list> 
</property> 
</bean> 




</beans> 

啟動后報錯: 
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'StudentMapper' defined in ServletContext resource [/WEB-INF/spring/appServlet/app-config.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in ServletContext resource [/WEB-INF/spring/appServlet/app-config.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.apache.ibatis.builder.xml.XMLConfigBuilder.<init>(Ljava/io/InputStream;Ljava/lang/String;Ljava/util/Properties;)V 

不知什么原因,請各位予以解答,謝謝!

15 樓 limingnihao 2011-03-11  

xiaojianhx 寫道

xiaojianhx 寫道

事務怎么加?




哦,寫錯了.....

是"事務怎么處理"
使用Spring的@Transactional注解,一般寫在Service層的接口方法上。

14 樓 xiaojianhx 2011-03-11  

xiaojianhx 寫道

事務怎么加?




哦,寫錯了.....

是"事務怎么處理"

13 樓 xiaojianhx 2011-03-11  

事務怎么加?

12 樓 小金哥 2010-11-26  

小金哥 寫道

xiaojianhx 寫道

我eclipse 啟動tomcat的時候報錯,怎么回事啊 

嚴重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException 

代碼: 

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
<property name="configLocation"> 
<value>classpath:mybatis-config.xml</value> 
</property> 
<property name="dataSource"> 
<ref bean="dataSource" /> 
</property> 
</bean>


 遇到相同的問題,調試了一晚上沒有找到原因,不知7樓是否已經解決該問題了?若解決了,請不吝賜教!
終於弄明白了,原來是spring版本的問題,MyBatis-Spring只能在spring3.0版本上使用,如果用spring3.0以下版本就會出現該問題,建議將spring升級為3.0或改用ibatis2.0!

11 樓 JavaScape 2010-11-09  

resultType 與resultMap 不能同時使用。  
官方使用手冊里好像有這么一句,但是你的配置文件中同時配置了這兩個屬性: 

<!-- 查詢學生,根據id --> 
13. <select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap"> 

請樓主解釋一下?

10 樓 小金哥 2010-10-31  

xiaojianhx 寫道

我eclipse 啟動tomcat的時候報錯,怎么回事啊 

嚴重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException 

代碼: 

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
<property name="configLocation"> 
<value>classpath:mybatis-config.xml</value> 
</property> 
<property name="dataSource"> 
<ref bean="dataSource" /> 
</property> 
</bean>


 遇到相同的問題,調試了一晚上沒有找到原因,不知7樓是否已經解決該問題了?若解決了,請不吝賜教!

 

源碼來源: minglisoft.cn/technology


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM