Mybatis(一)—實現對資料庫的增刪改查操作
阿新 • • 發佈:2019-01-10
1.Mybatis簡介
MyBatis 本是apache的一個開源專案iBatis, 2010年這個專案由apache software foundation 遷移到了google code,並且改名為MyBatis 。2013年11月遷移到Github。 MyBatis是一個優秀的持久層框架,它對jdbc的操作資料庫的過程進行封裝,使開發者只需要關注 SQL 本身,而不需要花費精力去處理例如註冊驅動、建立connection、建立statement、手動設定引數、結果集檢索等jdbc繁雜的過程程式碼。
Mybatis通過xml或註解的方式將要執行的各種statement(statement、preparedStatement、CallableStatement)配置起來,並通過java物件和statement中的sql進行對映生成最終執行的sql語句,最後由mybatis框架執行sql並將結果對映成java物件並返回。
2.環境搭建
需要匯入的jar包:
mybatis-3.2.7.jar
mysql-connector-java-5.1.7-bin.jar
需要的所有jar包:
建立資料庫和表:
在study資料庫建立中students表,表結構如下:
新增Mybatis的配置檔案sqlconfig.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置資料庫連線資訊 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/study" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
注意study是資料庫的名稱,其他的引數比如資料庫賬戶名,密碼。
該檔案建立在src目錄下。
3.建立表對應的實體類
Student程式碼如下:
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
private String tel;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex
+ ", age=" + age + ", tel=" + tel + "]";
}
}
4.sql對映檔案
該檔案建立在src目錄下。
<?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">
<!-- namespace:名稱空間,做sql隔離 ,訪問sql語句時,sql的id前面要帶著名稱空間-->
<mapper namespace="student">
<!--
id:sql語句唯一標識,不能重複。
parameterType:屬性指明查詢時使用的引數型別
resultType:屬性指明查詢返回的結果集型別。resultType="com.mq.pojo.Student"表示返回值是Student型別
#{}佔位符:起到佔位作用,如果傳入的是基本型別(string,long,double,int,boolean,float等),那麼#{}中的變數名稱可以隨意寫,一般和屬性名相同。
java.lang.Integer也可以直接寫成int
-->
<select id="findStuById" parameterType="java.lang.Integer" resultType="com.mq.pojo.Student">
select * from students where id=#{id}
</select>
<!--
如果返回結果為集合,可以呼叫selectList方法,這個方法返回的結果就是一個集合,所以對映檔案中應該配置成集合泛型的型別
${}拼接符:字串原樣拼接,如果傳入的引數是基本型別(string,long,double,int,boolean,float等),那麼${}中的變數名稱必須是value
注意:拼接符有sql注入的風險,所以慎重使用
-->
<select id="findStuByName" parameterType="java.lang.String" resultType="com.mq.pojo.Student">
select * from students where name like '%${value}%'
</select>
<!--
#{}:如果傳入的是pojo型別,那麼#{}中的變數名稱必須是pojo中對應的屬性,
如果要返回資料庫自增主鍵:可以使用select LAST_INSERT_ID()-->
<insert id="insertStu" parameterType="com.mq.pojo.Student" >
<!-- 執行 select LAST_INSERT_ID()資料庫函式,返回自增的主鍵
keyProperty:將返回的主鍵放入傳入引數的Id中儲存.
order:當前函式相對於insert語句的執行順序,在insert前執行是before,在insert後執行是AFTER
resultType:id的型別,也就是keyproperties中屬性的型別
-->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
</selectKey>
insert into students (name,sex,age,tel) values(#{name},#{sex},#{age},#{tel})
</insert>
<delete id="delStuById" parameterType="int">
delete from students where id=#{id}
</delete>
<!--傳入的是一個pojo型別,就是一個新的物件 -->
<update id="updateStuById" parameterType="com.mq.pojo.Student">
update students set name=#{name} where id=#{id}
</update>
</mapper>
在sqlconfig.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置資料庫連線資訊 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/study"/>
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 註冊Student.xml檔案,這兩個檔案在同一個目錄下,都在src目錄下-->
<mapper resource="Student.xml"/>
</mappers>
</configuration>
5.測試方法
public class StudentTest {
private SqlSessionFactory factory;
//作用:在測試方法前執行這個方法
@Before
public void FirstDo() throws Exception{
//載入配置檔案
String resource = "sqlconfig.xml";
//通過流將核心配置檔案讀取進來
InputStream inputStream = Resources.getResourceAsStream(resource);
//通過核心配置檔案輸入流來建立會話工廠
factory = new SqlSessionFactoryBuilder().build(inputStream);
}
/**
* 根據id查詢物件。
*/
@Test
public void findStuById(){//通過工廠建立會話
SqlSession openSession = factory.openSession();
//第一個引數:所呼叫的sql語句= namespace+.+sql的ID。
//查詢單個物件,使用selectOne方法即可
Student student = openSession.selectOne("student.findStuById", 4);
System.out.println(student);
openSession.close();
}
/**
* 通過name進行模糊查詢,返回結果應該是一個list集合,所以使用SqlSession的selectList方法。
*/
@Test
public void findStuByName(){//通過工廠建立會話
SqlSession openSession = factory.openSession();
//如果返回結果為集合,呼叫selectList方法,這個方法返回的結果就是一個集合
List<Student> list = openSession.selectList("student.findStuByName", "羽");
System.out.println(list);
openSession.close();
}
/**
* 插入資料,先建立表對應的物件,設定屬性,然後呼叫insert方法。
*/
@Test
public void insertStu(){//通過工廠建立會話
SqlSession openSession = factory.openSession();
Student student=new Student();
student.setAge(25);
student.setSex("女");
student.setTel("58938939");
student.setName("貂蟬");
openSession.insert("student.insertStu", student);
//提交事務(mybatis會自動開啟事務,但是它不知道何時提交,所以需要手動提交事務)
openSession.commit();
System.out.println("id值" + student.getId());
}
/**
* 通過id刪除資料
*/
@Test
public void delStuById(){
SqlSession openSession = factory.openSession();
//如果返回結果為集合,呼叫selectList方法,這個方法返回的結果就是一個集合
openSession.delete("student.delStuById", 5);
//提交事務
openSession.commit();
openSession.close();
}
/**
* 更新資料,需要新建立一個物件。
* 如果where條件是id,那麼這個物件就需要設定id屬性。
*/
@Test
public void updateStuById(){
SqlSession openSession = factory.openSession();
//如果返回結果為集合,呼叫selectList方法,這個方法返回的結果就是一個集合
Student student=new Student();
student.setId(2);
student.setName("劉備");
openSession.delete("student.updateStuById",student);
//提交事務
openSession.commit();
openSession.close();
}
}