1. 程式人生 > >IDEA使用JUNIT4實現SSM整合後的MyBatis的增刪改查

IDEA使用JUNIT4實現SSM整合後的MyBatis的增刪改查

第一步,配置好spring-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!--配置資料來源,因為MyBatis的元件被Spring管理了,所以,需要將資料來源也配成一個Bean-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/online_class?useUnicode=true&amp;characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="1234" />
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mapping.xml檔案 -->
        <property name="mapperLocations" value="classpath:mappers/*.xml"></property>
    </bean>

    <!--這個Bean能幫我們自動建立Mapper物件,並自動注入-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.qst.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

第二步:在對映檔案裡寫好SQL語句

<?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.qst.dao.UserMapper">
    <insert id="addUser" parameterType="com.qst.entity.User" >
      insert into user(firstName, mail, password, lastName) values (#{firstName},#{mail},#{password},#{lastName})
    </insert>
    <select id="select" parameterType="int" resultType="com.qst.entity.User">
        select * from user where id=#{id};
    </select>
    <delete id="deleteUser" parameterType="int" >
        delete from user where id=#{id};
    </delete>
    <update id="updateUser" parameterType="com.qst.entity.User">
        update user set firstName=#{firstName},mail=#{mail},password=#{password},lastName=#{lastName} where id=#{id}
    </update>
</mapper>

第三步,寫好介面類UserMapper.java與屬性類User.java

**UserMapper.java:**
package com.qst.dao;
import com.qst.entity.User;

public interface UserMapper {
//注意這裡除了select都是無返回值的!!!
    int addUser(User user);
   public User select(int id);
    void  deleteUser(int id);
    void  updateUser(User user5);

}

**User.java:**
package com.qst.entity;

public class User {
    private int id;
    private String firstName;
    private String mail;
    private String password;
    private String lastName;

    public User(int id, String firstName, String mail, String password, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.mail = mail;
        this.password = password;
        this.lastName = lastName;
    }

    @Override
    //這裡toString方法是用來後期的查詢語句將結果列印在控制檯上
    public String toString() {
        return "User{" +
                "id=" + id +
                ", firstName='" + firstName + '\'' +
                ", mail='" + mail + '\'' +
                ", password='" + password + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

第四步:編寫測試類,這裡先要寫一個配置JUNIT4的配置測試檔案:UserTestBase.java:

package qst;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ={"classpath:spring-context.xml"} )
abstract class UnitTestBase extends AbstractTransactionalJUnit4SpringContextTests {
}

然後寫最終的測試類UserTest.java:

package qst;

import com.qst.dao.UserMapper;
import com.qst.entity.User;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

import static org.junit.Assert.assertEquals;

public class UserTest extends UnitTestBase{
    @Autowired
    private UserMapper userMapper;
    @Test
    @Transactional
    //說明一下這裡為什麼不要回滾,如果回滾的話,是資料會顯示插入成功,但是開啟資料庫會發現沒有資料,所以不要回滾。
    @Rollback(false)
    public void testAddOneUser(){
        //測試新增一個使用者
     User user=new User(4,"王小龍","[email protected]","wsf7408261","wxl");
              int ret=userMapper.addUser(user);
              //驗證插入是否成功
        assertEquals(ret,1);
    }
    @Test
    public void testselectUser(){
       User user= userMapper.select(3);
        System.out.println(user);//直接列印在控制檯

    }
    @Test
    @Rollback(false)
    public void testdeleteUser(){

       userMapper.deleteUser(3);
    }
    @Test
    @Rollback(false)
    public void updateUser(){
       User user=new User(1,"wxl","wfghjuh","88888","lllong");
       userMapper.updateUser(user);
    }
}

這是我專案的子目錄:在這裡插入圖片描述 最後如果執行時控制檯報錯缺少Datasource時,找到IDEA最右邊的Datasource連線一下你自己的資料庫就可以解決了。在這裡插入圖片描述