《深入浅出MyBatis技术原理与实战》,ISBN:978-7-121-29594-2
1.加载数据库驱动
2.通过DriverManager获取数据库连接Connection
3.操作Connection打开Statement/PreparedStatement
4.通过Statement执行SQL
5.使用ResultSet读取数据
6.释放相关资源
1.工作量大,需要手动加载驱动、建立连接、执行SQL、处理结果、释放连接,重复代码多;
2.SQL通过字符串拼接的形式硬编码在代码中,不方便也不安全;
建表语句:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
maven:
<dependencies>
<!-- Contains Protobuf -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
</dependencies>
Example:
import java.sql.*;
public class PureJDBC {
public static void main(String[] args){
Connection connection = null;
try {
//Load jdbc driver
Class.forName("com.mysql.jdbc.Driver");
final String url = "jdbc:mysql://localhost:3306/mybatis";
final String username = "root";
final String password = "root";
//Get Connection
connection = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
//Create statement
statement = connection.prepareStatement("select * from user where id = ?");
statement.setLong(1,1L);
//Query result
resultSet = statement.executeQuery();
if(resultSet.next()){
final long id = resultSet.getLong("id");
final String name = resultSet.getString("name");
System.out.println(id + "," + name);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//Release resource
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
由于原生JDBC存在如上缺点,因此提出了对象关系映射(Object Relational Mapping),简称ORM。在Java中,ORM模型将数据库表和Java对象进行映射。
常用的ORM模型有:Hibernate、JOOQ、SpringData以及本文介绍之Mybatis。
S
Mybatis的前身是Apache的开源项目:ibatis,2010年该项目由apache sofeware foundation迁移到google code,并改名为Mybatis。并于2013年迁移到github,目前Mybatis由github维护。
mybatis_config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Mapper 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="user.xml"/>
</mappers>
</configuration>
user.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.UserMapper">
<select id="getUser" parameterType="long" resultType="mybatis.User">
select id , name from user where id = #{id}
</select>
</mapper>
User.java
package mybatis;
public class User {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
UserMapper.java
package mybatis;
public interface UserMapper {
public User getUser(final long id);
}
Example:
private static SqlSessionFactory sqlSessionFactory = null;
private SqlSessionFactory getSqlSessionFactory() {
if (null == sqlSessionFactory) {
final String resource = "mybatis_config.xml";
try {
Reader reader = Resources.getResourceAsReader(resource);
return new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
throw new IllegalStateException("Cannot build SqlSessionFactory", e);
}
} else {
return sqlSessionFactory;
}
}
public static void main(String[] args) {
final SqlSession sqlSession = new HelloWorldMyBatis().getSqlSessionFactory().openSession();
final UserMapper mapper = sqlSession.getMapper(UserMapper.class);
final User user = mapper.getUser(1L);
//User{id=1, name='Jerry'}
System.out.println(user);
sqlSession.close();
}