Mybatis把訪問資料庫的操作都封裝起來了,所以當我們使用Mybatis進行資料庫操作時,只需要提供SQL語句就可以了,程式碼的邏輯會變得非常清晰,書寫起來也很簡潔。
下面的例子都是基於上一篇文章
一、create操作
在user.xml檔案中新增
<insert id="addUser" parameterType="User">
insert into user (user_name, user_id, user_pwd, user_phone) values(#{user_name}, #{user_id}, #{user_pwd}, #{user_phone} )
</insert>
複製程式碼
程式碼中新增:
User user = new User();
user.setUser_name("Eve");
user.setUser_id("12345");
user.setUser_phone("13978992134");
user.setUser_pwd("1111111");
session.insert("addUser", user);
session.commit();
session.close();
複製程式碼
二、算了,CURD沒啥好寫的,把程式碼貼在這吧
user.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.learn.pojo">
<select id="listUser" resultType="User">
select * from user
</select>
<insert id="addUser" parameterType="User">
insert into user (user_name, user_id, user_pwd, user_phone) values(#{user_name}, #{user_id}, #{user_pwd}, #{user_phone} )
</insert>
<delete id="deleteUser" parameterType="User" >
delete from user where user_id= #{user_id}
</delete>
<select id="getUser" parameterType="String" resultType="User">
select * from user where id= #{user_id}
</select>
<update id="updateUser" parameterType="User" >
update user set name=#{user_name} where id=#{user_id}
</update>
</mapper>
複製程式碼
Test.java
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import com.learn.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Test {
public static void main(String[] args) throws IOException {
//宣告配置檔案地址
String resource = "mybatis-config.xml";
//得到輸入流
InputStream inputStream = Resources.getResourceAsStream(resource);
//建立sql會話工廠
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//開啟sql會話
SqlSession session = sqlSessionFactory.openSession();
//獲取查詢結果
List<User> lu = session.selectList("listUser");
for (User u : lu) {
System.out.println(u.getUser_name());
System.out.println(u.getUser_id());
System.out.println(u.getUser_phone());
System.out.println("------------------------");
}
//建立User物件
User user = new User();
user.setUser_name("Eve");
user.setUser_id("12345");
user.setUser_phone("13978992134");
user.setUser_pwd("1111111");
//插入記錄
session.insert("addUser", user);
//刪除記錄
session.delete("deleteUser", user);
//根據id選記錄
User newUserr = session.selectOne("getUser","10086");
//更新記錄
user.setUser_name("改過名的Eve");
session.update("updateUser",user);
session.commit();
session.close();
}
}
複製程式碼