如何在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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章