SSM学习之Mybatis(一)
SSM框架学习线路
- 第一部分:使用Mybatis取代JDBC、dbutils等原始方法操作数据库;
- 学习Spring框架理解IOC、AOP思想,使用Spring来管理对象、事务;
- 学习SpringMVC框架取代Servlet技术,整合三大框架,完成案例
MyBatis是什么?
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。总而言之,MyBatis是一个轻量级简化数据库操作的框架
学习目标:
- 了解Mybatis架构
- 掌握Mybatis框架搭建、配置
- 使用Mybatis完成对数据库的增、删、改、查操作
- 掌握Mapper代理开发
- 掌握动态SQL编写SQL语句
- 掌握输入和输出映射
- 掌握多表关联查询
回忆JDBC编程:
创建数据库连接、查询对象、结果集对象——>调用Class.forName创建结果集对象——>获取连接——>创建sql语句,获取statement——>查询输出结果——>遍历结果——>关闭资源
public class jdbcTest {
public static void main(String[] args) throws SQLException {
//创建链接
Connection connection = null;
//查询对象
PreparedStatement preparedStatement = null;
//结果集对象
ResultSet resultSet = null;
//加载数据库驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ssm_mybatis?useSSL=false", "root", "1234");
String sql = "select * from user where u_sex=?";
//获取statement
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "0");
resultSet = preparedStatement.executeQuery();
//查询输出结果
while (resultSet.next()) {
System.out.println(resultSet.getString("u_id")+" "+resultSet.getString("u_username")+" "+ resultSet.getString("u_sex"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(resultSet!=null) {
resultSet.close();
}
if (preparedStatement!=null) {
preparedStatement.close();
}
if (connection!=null) {
connection.close();
}
}
}
}
使用mybatis首先创建主配置文件
<configuration>
<environments default="development">
<environment id="development">
<!-- 使用jdbc的事务 -->
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 使用连接池 链接数据库 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm_mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
</configuration>
然后创建mapper的映射文件
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
No Instructor时要注意加入无参构造方法和重写ToString()方法
Mybatis的架构图
基于以上可知
首先要@Test来在Junit中创建测试用例
//测试入门程序,通过ID查询用户
public void Test1() throws IOException {
//读取配置文件
String resource="sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
//需要sqlSessionFactoryBuilder
SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
//创建sqlSessionfactory
SqlSessionFactory ssf = ssfb.build(in);
//生产一个sqlSession
SqlSession session = ssf.openSession();
//操作一个数据库 参数1:要操作的sql语句 参数2:sql语句的参数
User user = session.selectOne("UserMapper.selectUserById",1);
System.out.println(user);
运行结果