關于MyBatis這里不再介紹,直接開始動手。
編輯器:InteIIiJ IDEA, 數據庫:mysql
1.新建一個maven項目
pom.xml中添加mysql和mybatis依賴
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>
2. 在mysql中新建一個testdb數據庫,和一張person表
create database testdb;
use testdb;
create table person (
id int auto_increment primary key not null,
name varchar(20) not null,
age int not null,
sex varchar(10) not null
) default charset=utf8;
注意定義表的最后指定utf8編碼,同時后面指定數據源的時候也會指定utf-8編碼,這樣才能支持中文。
3.最后的目錄結構
4.下面介紹一下每個文件的作用和用途
首先,定義一個實體類Person,注意要和數據庫中的字段一一對應。
public class Person {
private int id;
private String name;
private int age;
private SEX sex;
// 構造方法和set,get方法請自行添加
}
public enum SEX {
MAN, WOMAN
}
然后,定義所有sql操作的mapper映射文件(PersonMapper.xml)如下:
resultType指定sql語句的返回值類型,parameterType用來指定參數類型
mapper的namespace這里暫時隨便寫,后面會介紹它的作用。
sql 語句語句中的參數用#{}來修飾
<?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="suibianxiede">
<select id="selectPerson"
resultType="Person" parameterType="Person">
SELECT *
FROM Person
WHERE id = #{id}
</select>
<select id="selectPersonByName"
resultType="Person">
SELECT *
FROM Person
WHERE name = #{name}
</select>
<!--在插入的時候指定useGeneratedKeys="true",讓數據庫自動生成主鍵。-->
<insert id="insertPerson"
useGeneratedKeys="true">
INSERT INTO Person (name, age, sex) VALUES (#{name}, #{age}, #{sex})
</insert>
<update id="updatePerson">
UPDATE Person
SET age = #{age}
WHERE id = #{id}
</update>
<delete id="deletePerson">
DELETE FROM Person
WHERE id = #{id}
</delete>
</mapper>
定義mybatis的配置文件(mybatis-config.xml),用來指定數據源,引入mapper映射文件,系統配置等等
<?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>
<!--指定屬性, 在environment中引用-->
<properties>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="driver.useSSL" value="false"/>
</properties>
<!--系統設置-->
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
<!--指定別名,這樣在mapper映射文件中就可以直接使用Person,而不用使用com.archer.mybatis.Person這種全路徑名-->
<typeAliases>
<typeAlias type="com.archer.mybatis.Person" alias="Person"/>
</typeAliases>
<!--配置環境,可以配置多個環境用于測試、調試和生產-->
<!--這里environments的default字段一定要和下面的所有的environment中的一個的id字段一致,表示選用哪種數據庫環境,不然在獲取sqlsession的時候會報空指針錯誤-->
<!--### Error opening session. Cause: java.lang.NullPointerException-->
<!--### Cause: java.lang.NullPointerException-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--配置mapper映射文件-->
<mappers>
<mapper resource="PersonMapper.xml"/>
</mappers>
</configuration>
創建SqlSessionFactory(Utils):
package com.archer.mybatis;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by git on 2017/3/27.
*/
public abstract class Utils {
private static volatile SqlSessionFactory sqlSessionFactory;
public static final String configLocation = "mybatis-config.xml";
public static SqlSessionFactory getSqlSessionFactory() throws IOException {
if (sqlSessionFactory == null) {
synchronized (Utils.class) {
if (sqlSessionFactory == null) {
InputStream inputStream = Resources.getResourceAsStream(configLocation);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
inputStream.close();
}
}
}
return sqlSessionFactory;
}
}
結下來,開始操作mybatis:
在創建SQLSessionFactory之后,我們需要獲取MyBatis最核心的對象SqlSession,所有操作都需要SqlSession來進行。另外它是非線程安全的對象,不能放在類的靜態字段上,最好也不要作為實例字段。我們要在需要的時候創建它,不用的時候及時釋放。
public class Main {
private static SqlSessionFactory sqlSessionFactory;
public static void main(String[] args) {
SqlSession sqlSession;
try {
sqlSessionFactory = Utils.getSqlSessionFactory();
sqlSession = sqlSessionFactory.openSession(true);
//插入數據
Person p = new Person(-1, "老劉", 152, SEX.MAN);
sqlSession.insert("insertPerson",p);
//檢索數據
Person s = sqlSession.selectOne("selectPersonByName", p.getName());
System.out.println(s);
//更新數據
s.setAge(260);
sqlSession.update("updatePerson", s);
Person s2 = sqlSession.selectOne("selectPersonByName", p.getName());
System.out.println(s2);
//刪除數據
sqlSession.delete("deletePerson", s.getId());
//最后,不使用的時候記得把sqlSession釋放掉
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5.創建映射類
在上面的例子中,我們操作sql語句都是通過id對應的字符串來完成,這中方式比較笨拙,Mybatis提供了一種更加方便的方法來操作sql,那就是映射類。
定義一個接口類,接口中的方法名字必須和映射文件中的語句id一致,包括參數。
public interface PersonMapper {
Person selectPerson(int id);
Person selectPersonByName(String name);
void insertPerson(Person person);
void updatePerson(Person person);
void deletePerson(Person person);
}
接下來,我們好要修改映射文件的mapper的namespace(前面提到過,一開始是隨便寫的),將命名空間修改為映射類的類名就能讓Mybatis找到這個映射文件了。
<mapper namespace="com.archer.mybatis.PersonMapper">
配置好映射類和映射文件之后,就可以使用了,只需要通過sqlSession獲取到映射類即可:
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
Person p = new Person(-1, "老劉", 152, SEX.MAN);
mapper.insertPerson(p);