Mybatis框架(十一)Mybatis用註解實現CRUD

Mybatis用註解實現CRUD、這裏只作具體的實現過程。前期創建項目等工作不再介紹。
一、我們首先可以在工具類創建的時候實現自動提交事務。

package com.wst.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try{
            //使用mybatis第一步、獲取sqlSessionFactory對象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
    //返回sqlsession對象
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
}

在這裏插入圖片描述
二、編寫接口,並增加註解。

package com.wst.dao;
import com.wst.pojo.Stu;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface StuMapper {
     //查找學生全部信息
     @Select(value = "select * from stu")
     List<Stu> getStus();
     //根據id查找學生的信息
     //方法存在多個參數,所有的參數前面必須加上@Param註解
     @Select("select * from stu where id = #{id}")
     Stu getStuByID(@Param("id")int id);
     //插入學生信息
     @Insert("insert into stu(id,name,age,add) values (#{id},#{name},#{age},#{add})")
     int addStu(Stu stu);
     //更改學生信息
     @Update("update stu set name = #{name},age = #{age}, add=#{add} where id = #{id}")
     int updateStu(Stu stu);
     //刪除學生信息
     @Delete("delete from stu where id = #{id}")
     int deleteStu(@Param("id") int id);
}

三、在Mybatis的核心配置文件中,綁定接口。

     <mappers>     
        <mapper class="com.wst.dao.StuMapper" />
    </mappers>

四、編寫測試類、進行測試。

public class StuMapperTest {
    @Test
    public void test(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
       StuMapper mapper = sqlSession.getMapper(StuMapper.class); 
         
       //查找學生的全部信息
        List<Stu> stuList = mapper.getStus();
        for (Stu stu : stuList) {
            System.out.println(stu);
        }
        
       //根據學生的id查詢學生的信息
        Stu stuByID = mapper.getStuByID(1);
        System.out.println(stuByID);
       
       //增加學生信息
        mapper.addStu(new Stu(12,"張三",12,"陝西"));
        
        //更改學生信息
        mapper.updateStu(new Stu(12,"張三",13,"陝西"));
        
        //刪除學生信息
        mapper.deleteStu(12);
        
        sqlSession.close();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章