本片博文从传统jdbc方式引出mybatis,进而讲解mybatis如何使用。
1.jdbc使用方式
(此处仅列出核心代码)
/**
jdbc工具类
**/
public class DBUtils {
public static Connection openConnection() {
Class.forName(DRIVERNAME);
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}
/**
userJdbc
**/
public class UserJdbc {
public void insertUser(User user){
Connection connection = DBUtils.openConnection();
String sql = "insert into user(username,age) value(?,?)";
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,user.getUsername());
preparedStatement.setInt(2,user.getAge());
preparedStatement.executeUpdate();
} catch (SQLException e) {
logger.error("预编译sql出错",e);
} finally {
DBUtils.closeConnection(connection);
}
}
public User selectUserOne(int id) throws SQLException {
Connection connection = DBUtils.openConnection();
String sql = "select id,username,age,phone,`desc` from user where id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,id);
ResultSet resultSet = preparedStatement.executeQuery();
/**
* @notice 此处需要手动将结果集映射
**/
if(resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt(1));
user.setUsername(resultSet.getString(2));
user.setAge(resultSet.getInt(3));
user.setPhone(resultSet.getString(4));
user.setDesc(resultSet.getString(5));
return user;
}
return null;
}
}
2.mybatis与jdbc对比
- 传统jdbc没有用数据库连接池,需要频繁创建连接,关闭连接,消耗系统资源。
- jdbc无法将结果集映射成对象。
- 使用 PreparedStatement设置参数时,需要1/2/3等数字标识参数顺序
- 总体来说api操作比较麻烦.
3.mybatis基本使用
- 引入maven依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
- 配置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>
<properties resource="jdbc.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
<mapper class="com.dck.mapper.UserMapperAnnotation"/>
</mappers>
</configuration>
- mapper文件
(举例UserMapper.xml)
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dck.mapper.UserMapper">
<select id="selectUserById" resultType="com.dck.pojo.User">
select id ,username,age,phone,`desc` from user where id = #{id}
</select>
</mapper>
- 创建sqlsessionfactory
String resource = "mybatis-config.xml";
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//以下任意一种方式均可
User user1 = (User)sqlSession.selectOne("com.dck.mapper.UserMapper.selectUserById", 1);
//推荐此种方式
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectUserById(1);
至此完成mybatis的部署
4.mybatis全局配置详解
属性名 | 作用 |
---|---|
properties | 系统属性占用配置 |
settings | 用于修改mybatis的运行时行为 |
typeAliases | 类型别名 |
typeHandler | 类型处理器,用于将预编译语句(PrepareStatment)或结果集(ResultSet)中的jdbc类型转化为Java类型 |
ObjectFactory | 对象工厂,提供默认构造器或执行构造参数初始化目标类型的对象 |
plugins | 插件,Mybatis允许配置多个环境 |
databaseProvider | 数据库便是提供商 |
mapper | Sql映射文件 |
5. #{}与${}的区别
- #{}采用的是预编译方式,可以防止sql注入,推荐使用这个
- ${}也有其用处,比如动态拼接sql时,对于表名的处理可以使用${}