MyBatis框架零基礎快速入門案例詳解
MyBatis下載地址:https://github.com/mybatis/mybatis-3/releases
一、創(chuàng)建數(shù)據(jù)庫和表
數(shù)據(jù)庫名ssm,數(shù)據(jù)表student
mysql> create database ssm;
Query OK, 1 row affected (0.01 sec)
mysql> use ssm
Database changed
mysql> CREATE TABLE `student` (
-> `id` int(11) NOT NULL ,
-> `name` varchar(255) DEFAULT NULL,
-> `email` varchar(255) DEFAULT NULL,
-> `age` int(11) DEFAULT NULL,
-> PRIMARY KEY (`id`)
-> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected, 3 warnings (0.03 sec)
二、創(chuàng)建maven工程
1、pom.xml加入maven坐標
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> </dependencies>
2、加入maven插件
<build> <resources> <resource> <directory>src/main/java</directory><!--所在的目錄--> <includes><!--包括目錄下的.properties,.xml 文件都會掃描到--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>
三、代碼編寫
1、編寫Student實體類
創(chuàng)建包 com.Example.domain, 包中創(chuàng)建 Student 類
package com.bjpowernode.domain;
/**
* <p>Description: 實體類 </p>
* <p>Company: http://www.bjpowernode.com
*/
public class Student {
//屬性名和列名一樣
private Integer id;
private String name;
private String email;
private Integer age;
// set ,get , toString
}2、編寫DAO接口StudentDao
創(chuàng)建 com.Example.dao 包,創(chuàng)建 StudentDao 接口
package com.bjpowernode.dao;
import com.bjpowernode.domain.Student;
import java.util.List;
/*
* <p>Description: Dao 接口 </p>
* <p>Company: http://www.bjpowernode.com
*/
public interface StudentDao {
/*查詢所有數(shù)據(jù)*/
List<Student> selectStudents();
}3、編寫DAO接口Mapper映射文件StudentDao.xml。
- 在 dao 包中創(chuàng)建文件 StudentDao.xml
- 要 StudentDao.xml 文件名稱和接口 StudentDao 一樣,區(qū)分大小寫的一 樣。
<?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:必須有值,自定義的唯一字符串 推薦使用:dao 接口的全限定名稱 --> <mapper namespace="com.Example.dao.StudentDao"> <!-- <select>: 查詢數(shù)據(jù), 標簽中必須是 select 語句 id: sql 語句的自定義名稱,推薦使用 dao 接口中方法名稱, 使用名稱表示要執(zhí)行的 sql 語句 resultType: 查詢語句的返回結(jié)果數(shù)據(jù)類型,使用全限定類名 --> <select id="selectStudents" resultType="com.Example.domain.Student"> <!--要執(zhí)行的 sql 語句--> select id,name,email,age from student </select> </mapper>
4、創(chuàng)建MyBatis主配置文件
項目 src/main 下創(chuàng)建 resources 目錄,設置 resources 目錄為 resources root
創(chuàng)建主配置文件:名稱為 mybatis.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> <!--配置 mybatis 環(huán)境--> <environments default="mysql"> <!--id:數(shù)據(jù)源的名稱--> <environment id="mysql"> <!--配置事務類型:使用 JDBC 事務(使用 Connection 的提交和回 滾)--> <transactionManager type="JDBC"/> <!--數(shù)據(jù)源 dataSource:創(chuàng)建數(shù)據(jù)庫 Connection 對象 type: POOLED 使用數(shù)據(jù)庫的連接池 --> <dataSource type="POOLED"> <!--連接數(shù)據(jù)庫的四個要素--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/ssm"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <!--告訴 mybatis 要執(zhí)行的 sql 語句的位置--> <mapper resource="com/Example/dao/StudentDao.xml"/> </mappers> </configuration>
支持中文的url
jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8
四、創(chuàng)建測試類進行測試
1、創(chuàng)建測試類MyBatisTest
src/test/java/com/Example/ 創(chuàng)建 MyBatisTest.java 文件
/*
* mybatis 入門
*/
@Test
public void testStart() throws IOException {
//1.mybatis 主配置文件
String config = "mybatis-config.xml";
//2.讀取配置文件
InputStream in = Resources.getResourceAsStream(config);
//3.創(chuàng)建 SqlSessionFactory 對象,目的是獲取 SqlSession
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//4.獲取 SqlSession,SqlSession 能執(zhí)行 sql 語句
SqlSession session = factory.openSession();
//5.執(zhí)行 SqlSession 的 selectList()
List<Student> studentList =
session.selectList("com.bjpowernode.dao.StudentDao.selectStudents");
//6.循環(huán)輸出查詢結(jié)果
studentList.forEach( student -> System.out.println(student));
//7.關閉 SqlSession,釋放資源
session.close();
}List<Student> studentList =
session.selectList("com.bjpowernode.dao.StudentDao.selectStudents");
近似等價的 jdbc 代碼
Connection conn = 獲取連接對象
String sql=” select id,name,email,age from student”
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
2、配置日志功能
mybatis.xml 文件加入日志配置,可以在控制臺輸出執(zhí)行的 sql 語句和參數(shù)
<settings> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings>
五、增刪改操作
insert操作
(1)StudentDAO接口中的方法
int insertStudent(Student student);
(2)StudentDAO.xml加入sql語句
<insert id="insertStudent">
insert into student(id,name,email,age)
values(#{id},#{name},#{email},#{age})
</insert>(3)增加測試方法
@Test
public void testInsert() throws IOException {
//1.mybatis 主配置文件
String config = "mybatis-config.xml";
//2.讀取配置文件
InputStream in = Resources.getResourceAsStream(config);
//3.創(chuàng)建 SqlSessionFactory 對象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//4.獲取 SqlSession
SqlSession session = factory.openSession();
//5.創(chuàng)建保存數(shù)據(jù)的對象
Student student = new Student();
student.setId(1005);
student.setName("張麗");
student.setEmail("zhangli@163.com");
student.setAge(20);
//6.執(zhí)行插入 insert
int rows = session.insert(
"com.bjpowernode.dao.StudentDao.insertStudent",student);
//7.提交事務
session.commit();
System.out.println("增加記錄的行數(shù):"+rows);
//8.關閉 SqlSession
session.close();
}到此這篇關于MyBatis框架零基礎快速入門案例詳解的文章就介紹到這了,更多相關MyBatis 案例內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Elasticsearch常見字段映射類型之scaled_float解讀
這篇文章主要介紹了Elasticsearch常見字段映射類型之scaled_float解讀。具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
解決Java調(diào)用BAT批處理不彈出cmd窗口的方法分析
本篇文章是對Java調(diào)用BAT批處理不彈出cmd窗口的方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05
SpringBoot + Spring Security 基本使用及個性化登錄配置詳解
這篇文章主要介紹了SpringBoot + Spring Security 基本使用及個性化登錄配置詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
Springboot?內(nèi)部服務調(diào)用方式
這篇文章主要介紹了Springboot?內(nèi)部服務調(diào)用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03

