1.传统的JDBC编程
1.创建数据库
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.创建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代码
创建数据库链接
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;
}
创建关闭数据对象销毁方法
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();
}
}
从上面的代码中,我们可以看出传统的JDBC的整个过程是:
- 1.使用JDBC编程需要连接数据库,注册驱动和数据库信息
- 2.操作Connection,打开Statement对象
- 3,通过Statement对象执行SQL,返回结果到ResultSet对象
- 4.使用ResultSet读取数据,通过代码转换为具体的POJO对象
- 5.关闭数据库连接
缺点
- 1.需要先连接,然后处理JDBC底层事务
- 2.还需要操作Connection对象,Statement对象,ResultSet对象
- 3.还需要获取ResultSet对象进行对POJO的映射
- 4.还需要处理异常以及关闭数据资源
2.ORM框架
对于快速迭代的项目而言,增加了巨大的工作量。于是诞生了ORM(Object Relational Mapping)的概念
解决数据库数据和POJO对象的相互映射。可以迅速将数据库表的数据转化为POJO
3.MyBatis
Mybatis是一个半自动映射的框架,因为它需要手动进行匹配提供POJO、SQL和映射关系。
- MyBatis的映射文件包含
- SQL
- 映射规则
- POJO
4.实战代码
- 引入jar包
compile group: 'org.mybatis', name: 'mybatis', version: '3.4.4'
- 创建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);
}
- 创建UserMapper.xml文件
在resource文件夹下面创建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>
- 创建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,创建SqlsessionFactory类的实例
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建Sqlsession实例
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取User Dao的实例
UserDao dao = sqlSession.getMapper(UserDao.class);
User user = dao.getUser(1);
System.out.println(user.toString());
}
}