1.傳統(tǒng)的JDBC編程
1.創(chuàng)建數據庫
create database mybatis charset utf8 collate utf8_general_ci;
CREATE TABLE `tb_user` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(18) DEFAULT NULL,
`SEX` char(2) DEFAULT NULL,
`AGE` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
2.Java后臺代碼
- 1.引入mysql jar包
compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
- 2.創(chuàng)建java實體類型
public class User {
private int id;
private String name;
private String sex;
private int age;
//省略get set
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
- 3.編寫JDBC代碼
創(chuàng)建數據庫鏈接
private Connection getConnection() throws ClassNotFoundException, SQLException {
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mybatis";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
return connection;
}
創(chuàng)建關閉數據對象銷毀方法
private void close(ResultSet rs, Statement statement, Connection connection) throws SQLException {
if (rs != null && !rs.isClosed())
rs.close();
if (statement != null && !statement.isClosed())
statement.close();
if (connection != null && !connection.isClosed())
connection.close();
}
編寫獲取對象的方法
public User getUser(int id) throws SQLException {
User user = new User();
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
try {
connection = getConnection();
statement = connection.prepareStatement("select * from tb_user where id=?");
statement.setInt(1, id);
rs = statement.executeQuery();
while (rs.next()) {
int uId = rs.getInt("ID");
String name = rs.getString("NAME");
String sex = rs.getString("SEX");
int age = rs.getInt("AGE");
user.setId(uId);
user.setName(name);
user.setSex(sex);
user.setAge(age);
break;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
close(rs, statement, connection);
}
return user;
}
運行測試
public static void main(String[] args) {
try {
JdbcExample example = new JdbcExample();
User user = example.getUser(1);
System.out.println(user.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
從上面的代碼中,我們可以看出傳統(tǒng)的JDBC的整個過程是:
- 1.使用JDBC編程需要連接數據庫,注冊驅動和數據庫信息
- 2.操作Connection,打開Statement對象
- 3,通過Statement對象執(zhí)行SQL,返回結果到ResultSet對象
- 4.使用ResultSet讀取數據,通過代碼轉換為具體的POJO對象
- 5.關閉數據庫連接
缺點
- 1.需要先連接,然后處理JDBC底層事務
- 2.還需要操作Connection對象,Statement對象,ResultSet對象
- 3.還需要獲取ResultSet對象進行對POJO的映射
- 4.還需要處理異常以及關閉數據資源
2.ORM框架
對于快速迭代的項目而言,增加了巨大的工作量。于是誕生了ORM(Object Relational Mapping)的概念
解決數據庫數據和POJO對象的相互映射。可以迅速將數據庫表的數據轉化為POJO

ORM映射模型
3.MyBatis
Mybatis是一個半自動映射的框架,因為它需要手動進行匹配提供POJO、SQL和映射關系。
- MyBatis的映射文件包含
- SQL
- 映射規(guī)則
- POJO
4.實戰(zhàn)代碼
- 引入jar包
compile group: 'org.mybatis', name: 'mybatis', version: '3.4.4'
- 創(chuàng)建Dao User接口
package dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import model.User;
@Mapper
public interface UserDao {
User getUser(int id);
}
- 創(chuàng)建UserMapper.xml文件
在resource文件夾下面創(chuàng)建mapper文件夾
<?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="dao.UserDao">
<select id="getUser" parameterType="int" resultType="model.User">
select * from tb_user where id=#{id};
</select>
</mapper>
- 創(chuàng)建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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserDao.xml" />
</mappers>
</configuration>
- 操作代碼
import model.User;
import dao.UserDao;
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 java.io.IOException;
import java.io.InputStream;
/**
* Created on 2017-08-06.
*/
public class MyBatisClient {
public static void main(String[] args) throws IOException {
//讀取mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//初始化mybatis,創(chuàng)建SqlsessionFactory類的實例
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//創(chuàng)建Sqlsession實例
SqlSession sqlSession = sqlSessionFactory.openSession();
//獲取User Dao的實例
UserDao dao = sqlSession.getMapper(UserDao.class);
User user = dao.getUser(1);
System.out.println(user.toString());
}
}