第一章 Mybatis構建ORM應用
阿新 • • 發佈:2019-01-26
MyBatis 是支援普通 SQL 查詢,儲存過程和高階對映的優秀持久層框架。 MyBatis 消除了幾乎所有的 JDBC 程式碼和引數的手工設定以及對結果集的檢索。 MyBatis 可以使用簡單的XML或註解用於配置和原始對映,將介面和 Java 的 POJO( Plain Old Java Objects,普通的Java 物件)對映成資料庫中的記錄
專案例項
1. 建立專案,引入Mybatis所需jar包(資料庫包,mybatis包)
2. 建立資料庫資料(MySQL)
## 建立資料庫 CREATE DATABASE mybatis; ## 建立使用者 CREATE USER 'mjsw'@'localhost' IDENTIFIED BY 'mjsw'; COMMIT; ## 授權 GRANT ALL ON mybatis.* TO 'mjsw'@'localhost'; ## 使用指定資料庫 USE mybatis ## 建立表 CREATE TABLE stu( stuno INT PRIMARY KEY AUTO_INCREMENT, sname VARCHAR(20) NOT NULL, sex VARCHAR(8), bir DATE NOT NULL, phone VARCHAR(11) ); ## 插入資料 INSERT INTO stu VALUES(NULL,'Micro','man','1997-02-12','17742328212'); INSERT INTO stu VALUES(NULL,'Myth','man','1997-03-20','18629364523'); INSERT INTO stu VALUES(NULL,'Gider','woman','1996-09-15','15629345522'); INSERT INTO stu VALUES(NULL,'Rose','woman','1996-04-11','15675342569'); ## 查詢資料庫 SELECT * FROM stu;
3. 資料庫驅動配置檔案: MySQL.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
jdbc.user=mjsw
jdbc.password=mjsw
4. 新增mybatis配置檔案: mybatis-config.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> <!-- 引入外部配置properties檔案(JDBC連線的資訊) --> <properties resource="MySQL.properties"/> <!-- 為實體類定義別名:簡化sql對映的xml引用 --> <typeAliases> <typeAlias type="com.model.Student" alias="Student"></typeAlias> </typeAliases> <!-- 配置mybatis執行環境:預設開發者模式 --> <environments default="development"> <!-- 環境變數:開發者模式 --> <environment id="development"> <!-- 事務管理器:type="JDBC" 代表使用JDBC的提交和回滾來管理事務 --> <transactionManager type="JDBC"/> <!-- mybatis提供了3種資料來源型別,分別是:POOLED,UNPOOLED,JNDI --> <!-- POOLED 表示支援JDBC資料來源連線池 --> <!-- UNPOOLED 表示不支援資料來源連線池 --> <!-- JNDI 表示支援外部資料來源連線池 --> <dataSource type="POOLED"> <!-- 讀取引入的外部配置檔案中的資料:name屬性值是固定的 --> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.user}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <!-- 對映器:註冊,對映介面配置檔案 --> <mappers> <!-- 指定具體路徑的對映介面配置檔案資源 --> <mapper resource="com/mapper/StudentMapper.xml"></mapper> </mappers> </configuration>
5. 建立model實體物件: Student
package com.model; import java.sql.Date; /* * 資料庫物件的實體物件 */ public class Student { private int stuno; private String sname; private String sex; private Date bir; private String phone; public Student() { super(); // TODO Auto-generated constructor stub } public Student(int stuno, String sname, String sex, Date bir, String phone) { super(); this.stuno = stuno; this.sname = sname; this.sex = sex; this.bir = bir; this.phone = phone; } @Override public String toString() { return "Student [stuno=" + stuno + ", sname=" + sname + ", sex=" + sex + ", bir=" + bir + ", phone=" + phone + "]"; } public int getStuno() { return stuno; } public void setStuno(int stuno) { this.stuno = stuno; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBir() { return bir; } public void setBir(Date bir) { this.bir = bir; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
6. 建立方法介面和定義操作表的sql對映配置檔案並註冊
介面: IstudentMapper
package com.mapper;
import java.util.List;
import com.model.Student;
/*
* 資料庫方法介面----------->sql操作的對映檔案
*/
public interface IStudentMapper {
// 查詢所有學生資訊
public List<Student> findAll();
// 增加資訊
public int add(Student stu);
// 刪除資訊
public int delete(int id);
// 修改資訊
public int update(Student stu);
}
對映配置檔案: StudentMapper.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.mapper.IStudentMapper">
<!-- 介面對應的sql對映檔案 :配置完介面對映檔案之後需在mybatis配置檔案進行註冊-->
<!-- 執行查詢,將結果集資料存入集合中,需自定義返回結果集 -->
<resultMap type="Student" id="StudentList">
<id property="stuno" column="stuno" />
<result property="sname" column="sname" />
<result property="sex" column="sex" />
<result property="bir" column="bir" />
<result property="phone" column="phone" />
</resultMap>
<!-- 在各種標籤中的id屬性必須和介面中的方法名相同 , id屬性值必須是唯一的,不能夠重複使用 -->
<!-- parameterType屬性指明查詢時使用的引數型別 -->
<!-- resultType屬性指明查詢返回的結果值型別 -->
<!--#{}中的內容,為佔位符,當引數為某個JavaBean時,表示放置該Bean物件的屬性值 -->
<!-- 增,刪,改返回是影響的行數,不需要指定返回型別resultType-->
<!-- 增加資訊 -->
<insert id="add" parameterType="Student">
insert into stu values(null,#{sname},#{sex},#{bir},#{phone})
</insert>
<!-- 刪除資訊 -->
<delete id="delete" parameterType="Student">
delete from stu where stuno=#{stuno}
</delete>
<!-- 修改資訊 -->
<update id="update" parameterType="Student">
update stu set sname=#{sname},sex=#{sex},bir=#{bir},phone=#{phone} where stuno=#{stuno}
</update>
<!-- 查詢所有資訊 -->
<select id="findAll" resultMap="StudentList">
select * from stu
</select>
</mapper>
7. 工具類: DBTools
package com.util;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/*
* mybatis連線資料庫工具類
*/
public class DBTools {
private SqlSession sqlsession = null ;
// 連線資料庫,並返回介面
public Object getInterfaceSqlSession(Class<?> cls) throws IOException{
// ① 引入配置檔案,建立SqlSessionFactoryBuilder
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// ② builder建造SqlSessionFactory
SqlSessionFactory factory = builder.build(is);
// ③ factory得到SqlSession
this.sqlsession = factory.openSession();
// ④ 獲取介面物件,
Object obj = sqlsession.getMapper(cls);
return obj;
}
// 提交事務
public void commit(){
if(sqlsession!=null){
sqlsession.commit();
}
}
// 關閉
public void close(){
if(sqlsession!=null){
sqlsession.close();
}
}
}
8. 測試
package com.test;
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.mapper.IStudentMapper;
import com.model.Student;
import com.util.DBTools;
/*
* 測試
* */
public class Test {
public static void main(String[] args) throws IOException {
// 建立資料庫物件
DBTools db = new DBTools();
// 獲取介面
IStudentMapper ism =(IStudentMapper)db.getInterfaceSqlSession(IStudentMapper.class);
// 查詢
List<Student> list = ism.findAll();
for (Student stu : list) {
System.out.println(stu);
}
// 增加
try {
ism.add(new Student(0,"Lisa", "woman",
new Date(new SimpleDateFormat("yyyy-MM-dd").parse("1996-12-30").getTime())
, "17792364586"));
} catch (ParseException e) {
System.err.println("時間格式轉換失敗");
}
System.out.println("資料庫資料增加成功");
//修改
try {
ism.update(new Student(4,"Rose", "woman",
new Date(new SimpleDateFormat("yyyy-MM-dd").parse("1996-04-11").getTime())
, "12345678923"));
} catch (ParseException e) {
System.err.println("時間格式轉換失敗");
}
System.out.println("資料庫資料修改成功");
// 刪除
ism.delete(1);
System.out.println("資料庫資料刪除成功");
// 提交事務和關閉
db.commit();
db.close();
}
}