Mybatis-02(操作表的增刪改查)
阿新 • • 發佈:2018-12-13
回顧
1.瞭解定義,知道mybatis的作用 2.搭建簡單mybatis架構 3.寫出簡單的測試程式碼進行測試
對資料庫表進行操作
通過Mybatis-01的簡單介紹我們可以進行簡單的查詢操作,接下來我們對資料庫表的操作進行昇華。
- 插入資料
在src檔案下新建包(com.atguigu_mybatisTest),在包下新建xml檔案(userMapper)用來定義sql的對映檔案
<!--parameterType引數型別,對應包下的實體類--> <insert id = "addUser" parameterType="com.atguigu_mybatis.Test1.User"> <!-- value 裡必須寫物件裡main的某一個屬性--> insert into users(name,age)values(#{name},#{age} </insert>
在配置檔案中對新建的mapper檔案進行配置,使其能順利載入sql對映檔案mapper.xml檔案
<mappers>
<!--去找mapper的檔案位置-->
<mapper resource="com/atguigu/mybatis/test2/userMapper.xml"/>
</mappers>
在dao層進行呼叫
public class Test2 { @Test public void testAdd(){ String resource = "conf.xml"; InputStream is = Test.class.getClassLoader().getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); SqlSession session = factory.openSession(); String statement ="com.atguigu_mybatis.Test2.userMapper"+".addUser"; //將地址以引數的形式傳入,第一個id,我們不需要(-1) int insert = session.insert(statement,new User(-1,"kk",23)); session.commit(); System.out.println(insert); } }
結果展示
- 其他操作
<!--可按上述步驟進行簡單測試--> <delete id="deleteUser" parameterType="int"> delete from users where id=#{id} </delete> <update id="updateUser" parameterType="com.atguigu.day03_mybatis.Test1.User"> upsate users set name=#{name},age#{age}where id=#{id} </update>
<mappers>
<!--去找mapper的檔案位置-->
<!--注意在Mapper檔案裡註冊的是class,介面-->
<mapper class ="com.atguigu.mybatis.test3.UserMapper"/>
</mappers>
兩種方式
- 通過xml檔案來寫SQL語句
- 基於註解的實現,將sql語句寫到註解裡,再建立一個介面,並在conf.xml裡註冊一下
public interface UserMapper{
//將sql語句通過註解執行
@Insert("insert into users(name,age)values(#{name},#{age})")
public int add(User user);
public int deleteById(Int id);
public int update(User user);
public User getById(int id);
public List<User>getAll();
}
問題總結
在寫測試類的時候,發現測試類不能執行,並報錯 這時我們要引入Junit和hamcrest-core的jar包