如何在Spring項目中使用Mybatis

warning:下面一切的內容必需基于你的spring能正常使用,不能使用的你還是先不要看。。。zzz

一、準備工作##

  1. jar包下載
    mybatis-3.4.4.jar
    mybatis-spring-1.3.1.jar
    spring-jdbc-4.2.4.RELEASE.jar
    mysql-connector-Java-5.1.10.jar(由于我這里使用mysql為例)
    spring-tx-4.2.4.RELEASE.jar
  2. mysql建庫建表初始化數據
create database studentDB;
use studentDB;
create table student(id char(11) primary key,name varchar(30),age tinyint,sex char(1));
insert into student values('12014052074','xyh',21,'男');
insert into student values('1201405207x','xiaojiejie',18,'女');

二、定義bean類和dao接口以及映射XML文件##

1、bean(student.java)

@Component//該處注解該bean為一個spring托管的bean
public class Student {
    private String id;
    private String name;
    private byte age;
    private String sex;
    public String getId() {
        return id;
    }
    public void setId(String 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(byte age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    
}

2、 dao(studentDao.java)

public interface StudentDao {
    public int updateStudent(Student s);\\更新記錄接口方法
    public List<Student> getAllStudent();\\獲取所有表行記錄
}

3、XML(studentDao.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.xyh.dao.StudentDao">
    <update id="updateStudent" parameterType="com.xyh.beans.Student">
        update student set name=#{name},age=#{age},sex=#{sex} where id=#{id}
    </update>
    <resultMap type="com.xyh.beans.Student" id="students">
        <id column="id" property="id" jdbcType="CHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="TINYINT" />
        <result column="sex" property="sex" jdbcType="CHAR"/>
    </resultMap>
    <select id="getAllStudent" resultMap="students">
        select * from student
    </select>
</mapper>

mapper標簽的namespace屬性為該映射文件對應Dao接口類。
update標簽用于更新操作,id屬性為對應方法名,paramerType屬性為傳入方法的參數類型,標簽體為操作sql,#{x}為傳入參數bean的x屬性。
resultMap標簽定義返回映射集,由于select操作中返回的結果需要存儲為list集合,type屬性為集合中元素類型,id標簽對應數據庫主鍵列,column屬性為表中字段名,property為bean中屬性名,jdbcType為表字段類型(注意:并不是與表中類型名稱都一樣)
select 標簽用于查詢操作,id屬性對應方法名,resultMap屬性為返回類型,因為是結果集合,使用前面定義的resultMap。

4、mybatis.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>
    <mappers>
        <mapper resource="com/xyh/dao/StudentDao.xml"/>
    </mappers>
</configuration>

引入定義的studentDao.xml文件

三、配置spring.xml配置文件

1、配置mysql數據源

<bean id="dataSource"                   class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/newsDB?characterEncoding=UTF-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="12345"></property>
</bean>

2、配置會話工廠

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

3、配置studentDao

<bean id="studentDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
        <property name="mapperInterface" value="com.xyh.dao.StudentDao"></property>  
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>  
    </bean> 

好了,該配置該定義該準備的都完成了,讓我們來看看結果吧

四、 test##

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext atc = new ClassPathXmlApplicationContext("spring.xml");
        Student s = (Student) atc.getBean("student");
        s.setId("12014052074");
        s.setName("xyh");
        s.setAge((byte)22);
        s.setSex("男");
        
        StudentDao dao = (StudentDao) atc.getBean("studentDao");
        System.out.println(dao.updateStudent(s));
    }

}

輸出結果為1(影響數據行數),這時候去數據庫一看,噢,我又老了一歲了。。。zzz

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext atc = new ClassPathXmlApplicationContext("spring.xml");      
        StudentDao dao = (StudentDao) atc.getBean("studentDao");
        List<Student> students = dao.getAllStudent();
        System.out.println(students.size());
    }
}

輸出結果為2,數據集的數據size。
好了,到這里你還整合不了的話~~~~~~~~~~~你還是從頭再來吧。。。zzz

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,933評論 18 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,954評論 6 342
  • 什么是Spring Spring是一個開源的Java EE開發框架。Spring框架的核心功能可以應用在任何Jav...
    jemmm閱讀 16,550評論 1 133
  • 別人說的不一定是全的,有時不一定是對的。 沒有入群時,看什么公眾號都是一概吸收其內容,不管內部邏輯是否合理,除非是...
    云棫閱讀 279評論 2 2
  • POST請求比較常見的一種情況就是用戶名密碼登陸情況,這里介紹一種用程序登陸豆瓣賬號的流程。 在豆瓣需要我們輸入用...
    楚江數據閱讀 1,356評論 0 0