定位sql需要很長(zhǎng)的字符串,namespace+id的使用方式很容易出錯(cuò),因?yàn)槭莝tring類(lèi)型的,編譯時(shí)沒(méi)發(fā)檢查,寫(xiě)錯(cuò)運(yùn)行時(shí)才會(huì)拋出異常柳爽。所以,mybatis提供了一種非常好的設(shè)計(jì)方式來(lái)避免這種問(wèn)題碱屁,即Mapper接口磷脯。namespace的值統(tǒng)一為接口的全路徑。
接口開(kāi)發(fā)步驟:[]里是你自己需要的名字
1.修改映射文件[User]Mapper.xml
映射文件中的namspace的值是接口的包名+接口的類(lèi)名
dao.[User]MapperDao(綁定Mapper文件和接口的關(guān)系)
(Dao層就是和數(shù)據(jù)庫(kù)交互的)
2.創(chuàng)建[User]Mapper接口(interface)
2.1接口所在包的包名+接口名=[User]Mapper.xml中namespace的值
(綁定接口和映射文件的關(guān)系)
2.2接口中的方法名=[User]Mapper.xml中定義SQL的id值
(綁定了將要執(zhí)行的SQL的id)
2.3接口中的方法的返回值類(lèi)型和參數(shù)類(lèi)型要和UserMapper.xml
映射文件中resultType的類(lèi)型一致
3.在核心配置文件sqlMapConfig.xml的<mappers>中引入
<mappr resource="[mapper]/[User]Mapper.xml">
<mapper namespace="dao.UserMapperDao"></mapper>
獲取接口實(shí)現(xiàn)類(lèi)對(duì)象娩脾,getMapper方法能基于類(lèi)全名找到對(duì)應(yīng)名稱(chēng)空間赵誓,然后基于名稱(chēng)空間找到映射文件,最后基于你的方法在映射文件找到與元素id相同的方法柿赊。
UserMapperDao dao = session.getMapper(UserMapperDao.class);
1俩功、在mysql中執(zhí)行下面的sql
CREATE DATABASE mybatisdb;
USE mybatisdb;
CREATE TABLE USER(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(100),addr VARCHAR(100),age INT);
INSERT INTO USER VALUES(NULL,'張三','北京',28);
INSERT INTO USER VALUES(NULL,'李四','上海',30);
INSERT INTO USER VALUES(NULL,'王五','廣州',19);
2、創(chuàng)建maven工程
pom.xml輸入如下內(nèi)容碰声,保存更新項(xiàng)目
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.company</groupId>
<artifactId>mybatisv2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--添加mysql驅(qū)動(dòng)程序依賴(lài) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!--日志包依賴(lài) -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
3像下面的方式創(chuàng)建對(duì)應(yīng)的文件,在對(duì)應(yīng)的文件添加代碼
UserMapperDao接口
/usermapper/src/main/java/dao/UserMapperDao.java
注意:
1绑雄、 包名 + 類(lèi)名 = UserMapper.xml中namespace的值
2、 接口中方法名 = UserMapper.xml中定義的SQL的id值
3奥邮、 方法的返回值類(lèi)型(resultType)和參數(shù)類(lèi)型(parameterType或sql中的參數(shù)(parameterType可以不傳))要和UserMapper.xml映射文件中類(lèi)型一致
package dao;
import java.util.List;
import pojo.User;
/**
* 這個(gè)類(lèi)用來(lái)完成用戶(hù)表的業(yè)務(wù)
*
* @author Administrator
*
*/
public interface UserMapperDao {
// <select id="findAll" resultType="User">
// select * from user
// </select>
// 查詢(xún)所有表的所有數(shù)據(jù)
public List<User> findAll();
// <select id="count" resultType="int">
// select count(*) from user
// </select>
public int count();
// <select id="findOne" parameterType="int" resultType="User">
// select * from user where id=#{id}
// </select>
public User findOne(int id);
// <insert id="save" parameterType="User">
// insert into user values(null,#{name},#{addr},#{age})
// </insert>
public void save(User user);
// <update id="updateUser" parameterType="User" >
// update user <set> age=#{age}</set> <where>name=#{name}</where>
// </update>
public void updateUser(User user);
// <delete id="deleteUser" parameterType="User">
// delete from user where name=#{name}
// </delete>
public void deleteUser(User user);
}
User
/usermapper/src/main/java/pojo/User.java
package pojo;
/**
* 這個(gè)類(lèi)用來(lái)和user表做映射關(guān)系
* 要求:屬性名必須和表字段名保持一致
*/
public class User {
//id
private int id;
//用戶(hù)名
private String name;
//地址
private String addr;
//年齡
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", addr=" + addr + ", age=" + age + "]";
}
}
UserMapper
/usermapper/src/main/resources/mapper/UserMapper.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">
<!--映射文件,寫(xiě)SQL罗珍,namespace唯一標(biāo)識(shí) -->
<mapper namespace="dao.UserMapperDao">
<!--查詢(xún)所有記錄
id唯一標(biāo)識(shí)
resultType把結(jié)果封裝在對(duì)象上洽腺,要寫(xiě)類(lèi)的全路徑-->
<select id="findAll" resultType="User">
select * from user
</select>
<select id="count" resultType="int">
select count(*) from user
</select>
<!--根據(jù)id查詢(xún)記錄-->
<select id="findOne" parameterType="int" resultType="User">
select * from user where id=#{id}
</select>
<!--新增一條記錄 -->
<insert id="save" parameterType="User">
insert into user values(null,#{name},#{addr},#{age})
</insert>
<!--修改指定記錄
動(dòng)態(tài)取值:#{age}
age就是user對(duì)象的age屬性
-->
<update id="updateUser" parameterType="User" >
update user <set> age=#{age}</set> <where>name=#{name}</where>
</update>
<delete id="deleteUser" parameterType="User">
delete from user where name = #{name}
</delete>
</mapper>
db.properties
/usermapper/src/main/resources/db.properties
driver:com.mysql.jdbc.Driver
url:jdbc:mysql:///mybatisdb
username:root
password:123456
log4j.properties
/usermapper/src/main/resources/log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
sqlMapConfig.xml
/usermapper/src/main/resources/sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--xml約束信息-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入數(shù)據(jù)源的配置文件
resource指定文件的位置-->
<properties resource="db.properties"></properties>
<!-- 設(shè)置別名 -->
<typeAliases>
<typeAlias type="pojo.User" alias="User"/>
</typeAliases>
<!-- 配置開(kāi)發(fā)環(huán)境 ,default用來(lái)設(shè)置默認(rèn)的開(kāi)發(fā)環(huán)境-->
<environments default="test">
<!--測(cè)試環(huán)境-->
<environment id="test">
<!--事務(wù)管理器:mybatis的事務(wù)交個(gè)jdbc處理-->
<transactionManager type="jdbc"></transactionManager>
<!--連接池:配置數(shù)據(jù)源覆旱,連接池 -->
<dataSource type="pooled">
<!--數(shù)據(jù)庫(kù)驅(qū)動(dòng)的名字-->
<property name="driver" value="${driver}"/>
<!-- 數(shù)據(jù)庫(kù)的url地址-->
<property name="url" value="${url}"/>
<!-- 數(shù)據(jù)庫(kù)的用戶(hù)名-->
<property name="username" value="${username}"/>
<!-- 數(shù)據(jù)庫(kù)的密碼-->
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件 -->
<mappers>
<!--引入U(xiǎn)serMapper文件
resource指定文件的位置
-->
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
InterfaceTest.java
/usermapper/src/test/java/test/InterfaceTest.java
package test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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.junit.Before;
import org.junit.Test;
import dao.UserMapperDao;
import pojo.User;
/**
* 這個(gè)類(lèi)用來(lái)測(cè)試Mapper接口
* @author Administrator
*
*/
public class InterfaceTest {
SqlSessionFactory ssf=null;
@Before
public void init(){
//獲取會(huì)話(huà)工廠
try {
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
ssf = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
//查詢(xún)user表的所有數(shù)據(jù)
@Test
public void findAll(){
//獲取sqlsession蘸朋,執(zhí)行SQL
SqlSession session = ssf.openSession();
//利用接口方法
UserMapperDao dao = session.getMapper(UserMapperDao.class);
List<User> list = dao.findAll();
//處理結(jié)果
for (User user : list) {
System.out.println(user);
}
//釋放資源
session.close();
}
@Test
public void count() {
// 2.創(chuàng)建sqlsession對(duì)象,執(zhí)行sql
SqlSession session = ssf.openSession();
UserMapperDao dao = session.getMapper(UserMapperDao.class);
int i = dao.count();
// 3.處理結(jié)果
System.out.println("count=" + i);
// 4.釋放資源
session.close();
}
//根據(jù)id查詢(xún)記錄
@Test
public void findOne(){
// 2.創(chuàng)建sqlsession對(duì)象,執(zhí)行sql
SqlSession session = ssf.openSession();
UserMapperDao dao = session.getMapper(UserMapperDao.class);
User user=dao.findOne(1);
System.out.println(user);
// 4.釋放資源
session.close();
}
//新增一條記錄
@Test
public void save(){
//創(chuàng)建sqlsession,執(zhí)行sql
SqlSession session = ssf.openSession();
UserMapperDao dao = session.getMapper(UserMapperDao.class);
//利用sqlsession執(zhí)行插入的sql
User user=new User();
user.setName("張三");
user.setAge(28);
user.setAddr("河北");
dao.save(user);
session.commit();
//釋放資源
session.close();
}
//修改指定記錄
@Test
public void updateUser(){
//創(chuàng)建sqlsession,執(zhí)行sql
SqlSession session = ssf.openSession();
UserMapperDao dao = session.getMapper(UserMapperDao.class);
User user=new User();
user.setAge(9);
user.setName("張三");
dao.updateUser(user);
session.commit();
//釋放資源
session.close();
}
//刪除指定記錄
@Test
public void deleteUser(){
//創(chuàng)建sqlsession,執(zhí)行sql
SqlSession session = ssf.openSession(true);
UserMapperDao dao = session.getMapper(UserMapperDao.class);
User user=new User();
user.setName("張三");
dao.deleteUser(user);
session.close();
}
}
如果在User類(lèi)中加入輸出System.out.println("User.setId()");
public void setId(int id) {
System.out.println("User.setId()");
this.id = id;
}
DEBUG [main] - ==> Preparing: select * from user
DEBUG [main] - ==> Parameters:
User.setId()
User.setId()
User.setId()
User.setId()
User.setId()
DEBUG [main] - <== Total: 5
User [id=1, name=張三, addr=北京, age=28]
User [id=2, name=李四, addr=上海, age=6]
User [id=3, name=王五, addr=廣州, age=19]
User [id=4, name=張三, addr=河北, age=28]
User [id=5, name=張三, addr=河北, age=28]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4973813a]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4973813a]
DEBUG [main] - Returned connection 1232306490 to pool.
會(huì)發(fā)現(xiàn)底層會(huì)調(diào)用類(lèi)的set方法,不過(guò)當(dāng)set方法不存在是,底層會(huì)直接通過(guò)反射為私有屬性賦值