本文目的
- 配置mybatis設定檔
- 示範基本查詢、新增、修改、刪除操作
一、前置操作,配置pom.xml,下載必要jar包
pom.xml檔案內容
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
說明:
前兩個為log配置,其實非必要,純粹為個人習慣。
第三個為mybatis,必需下載
第四個為mysql驅動程式,如果使用mysql必需下載。
二、配置mybatis-config.xml
檔名: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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 數據庫連接,由mybatis管理-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/zjh?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="xxxxx" />
</dataSource>
</environment>
</environments>
<!-- tb_userinfo 資料表配置 -->
<mappers>
<mapper resource="config/tb_userinfoMapper.xml"/>
</mappers>
</configuration>
說明:
<property name="driver" value="com.mysql.jdbc.Driver" />
呼叫mysql的驅動,就是剛剛下載的mysql-connector-java
<property name="url" value="jdbc:mysql://localhost:3306/zjh?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC" />
資料庫連線參數
localhost:3306 :連線本機資料庫,port為3306
zjh :是資料庫名稱
useUnicode=true&characterEncoding=utf-8 :是為了防止傳中文出現亂碼
serverTimezone=UTC :因為我們下載的mysql-connector-java為最新的8.0.12版,必需加上時區才不會拋錯。
<property name="username" value="root" />
<property name="password" value="xxxxxx" />
<property name="password" value="xxxxxx" />
賬號跟密碼。
<mappers>
<mapper resource="config/tb_userinfoMapper.xml"/>
</mappers>
<mapper resource="config/tb_userinfoMapper.xml"/>
</mappers>
mapper設定檔,因為我創了一個資料表,叫做tb_userinfo,所以設定的名字取名為tb_userinfoMapper.xml,比較好認。具體細節下一小節說明。
三.配置Mapper.xml
主要需要檔案有三個
- pojo,對應資料表的檔案
- Mapper.xml 設定sql的語法
- Interface,設定資料庫的配合資料庫語法
在配置檔案前,我們先創建資料表,裡面只有三個欄位id、username、age。
create table `tb_userinfo`(
`id` char(2) COLLATE utf8_unicode_ci NOT NULL,
`userName` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
第一個步驟,根據資料表開始創建POJO。
檔名:TB_UserInfo.java
package mybatis.pojo;
public class TB_UserInfo {
private String id;
private String userName;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
第二個步驟,我們開始創建Mapper.xml
檔名:tb_userinfoMapper.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="mybatis.sqlmap.TB_UserInfoMapper">
<select id="select1" parameterType="string" resultType="mybatis.pojo.TB_UserInfo">
SELECT * FROM tb_userinfo WHERE id=#{id}
</select>
<insert id="insert1" parameterType="mybatis.pojo.TB_UserInfo">
insert into tb_userinfo(id,userName,age)values(#{id},#{userName},#{age});
</insert>
<update id="update1" parameterType="mybatis.pojo.TB_UserInfo">
update tb_userinfo set userName = #{userName} WHERE id=#{id}
</update>
<delete id="delete1" parameterType="string">
delete FROM tb_userinfo WHERE id=#{value}
</delete>
</mapper>
第三個步驟,我們開始創建Interface
檔名:TB_UserInfoMapper.java
package mybatis.sqlmap;
import mybatis.pojo.TB_UserInfo;
public interface TB_UserInfoMapper{
public TB_UserInfo select1(String id);
public int insert1(TB_UserInfo tb_userinfo);
public int delete1(String id);
public int update1(TB_UserInfo tb_userinfo);
}
四、建立資料庫連線
建立mybatis連線,主要需要的是下面三個class。
- SqlSessionFactoryBuilder:讀取設定檔,並創建SqlSessionFactory,創建完SqlSessionFactory,它就沒用途了。
- SqlSessionFactory:工廠,當我們要對資料庫連線的時候,就需要使用它來創建SqlSession
- SqlSession:執行資料庫語法,除查詢、新增、修改、刪除外,包含commit和rollback都交由他控制。
下面為創建SqlSessionFactoryBuilder創建SqlSessionFactory的語法
private static SqlSessionFactory sqlSessionFactory = null;
static {
String resource = "config/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
五、執行查詢、新增、修改、刪除操作
查詢語法
/**
* 查詢語法
*/
public void selectSqlSession() {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
TB_UserInfoMapper tb_userinfoMapper = sqlSession.getMapper(TB_UserInfoMapper.class);
TB_UserInfo tb_UserInfo = tb_userinfoMapper.select1("A1");
System.out.println(tb_UserInfo.getUserName());
}catch(Exception e ) {
e.printStackTrace();
}finally {
if(sqlSession != null) {
sqlSession.close();
sqlSession = null;
}
}
}
新增語法
/**
* 插入語法
*/
public void insertSqlSession() {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
TB_UserInfoMapper tb_userinfoMapper = sqlSession.getMapper(TB_UserInfoMapper.class);
TB_UserInfo tb_userinfo = new TB_UserInfo();
tb_userinfo.setId("A2");
tb_userinfo.setAge(36);
tb_userinfo.setUserName("小米");
tb_userinfoMapper.insert1(tb_userinfo);
sqlSession.commit();
}catch(Exception e ) {
sqlSession.rollback();
e.printStackTrace();
}finally {
if(sqlSession != null) {
sqlSession.close();
sqlSession = null;
}
}
}
修改語法
/**
* 更新語法
*/
public void updateSqlSession() {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
TB_UserInfoMapper tb_userinfoMapper = sqlSession.getMapper(TB_UserInfoMapper.class);
TB_UserInfo tb_userinfo = new TB_UserInfo();
tb_userinfo.setId("A2");
tb_userinfo.setUserName("小明");
tb_userinfoMapper.update1(tb_userinfo);
sqlSession.commit();
}catch(Exception e ) {
sqlSession.rollback();
e.printStackTrace();
}finally {
if(sqlSession != null) {
sqlSession.close();
sqlSession = null;
}
}
}
刪除語法
/**
* 刪除語法
*/
public void deleteSqlSession() {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
TB_UserInfoMapper tb_userinfoMapper = sqlSession.getMapper(TB_UserInfoMapper.class);
tb_userinfoMapper.delete1("A2");
sqlSession.commit();
}catch(Exception e ) {
sqlSession.rollback();
e.printStackTrace();
}finally {
if(sqlSession != null) {
sqlSession.close();
sqlSession = null;
}
}
}
以上就是我們使用mybatis進行最簡單的查詢、新增、修改、刪除最簡單的範例。
最後,我們在附上最後一直程式完整的程式碼跟以及專案目錄。
專案目錄
mybatisTest.java
package testmybatis;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import mybatis.pojo.TB_UserInfo;
import mybatis.sqlmap.TB_UserInfoMapper;
public class MybatisTest {
private static Logger log = LoggerFactory.getLogger(MybatisTest.class);
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
if(sqlSessionFactory == null) {
synchronized (MybatisTest.class) {
if(sqlSessionFactory == null) {
String resource = "config/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
}
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
/**
* 查詢語法
*/
public void selectSqlSession() {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
TB_UserInfoMapper tb_userinfoMapper = sqlSession.getMapper(TB_UserInfoMapper.class);
TB_UserInfo tb_UserInfo = tb_userinfoMapper.select1("A1");
System.out.println(tb_UserInfo.getUserName());
}catch(Exception e ) {
e.printStackTrace();
}finally {
if(sqlSession != null) {
sqlSession.close();
sqlSession = null;
}
}
}
/**
* 插入語法
*/
public void insertSqlSession() {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
TB_UserInfoMapper tb_userinfoMapper = sqlSession.getMapper(TB_UserInfoMapper.class);
TB_UserInfo tb_userinfo = new TB_UserInfo();
tb_userinfo.setId("A2");
tb_userinfo.setAge(36);
tb_userinfo.setUserName("小米");
tb_userinfoMapper.insert1(tb_userinfo);
sqlSession.commit();
}catch(Exception e ) {
sqlSession.rollback();
e.printStackTrace();
}finally {
if(sqlSession != null) {
sqlSession.close();
sqlSession = null;
}
}
}
/**
* 更新語法
*/
public void updateSqlSession() {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
TB_UserInfoMapper tb_userinfoMapper = sqlSession.getMapper(TB_UserInfoMapper.class);
TB_UserInfo tb_userinfo = new TB_UserInfo();
tb_userinfo.setId("A2");
tb_userinfo.setUserName("小明");
tb_userinfoMapper.update1(tb_userinfo);
sqlSession.commit();
}catch(Exception e ) {
sqlSession.rollback();
e.printStackTrace();
}finally {
if(sqlSession != null) {
sqlSession.close();
sqlSession = null;
}
}
}
/**
* 刪除語法
*/
public void deleteSqlSession() {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
TB_UserInfoMapper tb_userinfoMapper = sqlSession.getMapper(TB_UserInfoMapper.class);
tb_userinfoMapper.delete1("A2");
sqlSession.commit();
}catch(Exception e ) {
sqlSession.rollback();
e.printStackTrace();
}finally {
if(sqlSession != null) {
sqlSession.close();
sqlSession = null;
}
}
}
public static void main(String[] args) {
try {
MybatisTest mabatisTest = new MybatisTest();
mabatisTest.selectSqlSession();
mabatisTest.insertSqlSession();
mabatisTest.updateSqlSession();
mabatisTest.deleteSqlSession();
} catch (Exception e) {
e.printStackTrace();
}
}
}
因為很多文章是過往自己搜集的資料、圖片,如有侵權疑慮請告知,將立即下架刪除。