1、JDBC方式
package com.kdy.tests;
import com.kdy.pojo.Emp;
import org.junit.Test;
import java.sql.*;
public class JDBCTest {
@Test
public void jbjc() throws ClassNotFoundException, SQLException {
//1、注册驱动
Class aClass1 = Class.forName("com.mysql.cj.jdbc.Driver");
//2、创建数据库链接 DriverManager.getConnect() 方法 获取数据库链接
String url = "jdbc:mysql://localhost:3306/mybatis";
String username = "root";
String password = "root";
//3、获取链接
Connection connection = DriverManager.getConnection(url, username, password);
//SQL语句
String sql = "SELECT * from EMP where id=?";
//4、使用PreparedStatement 解析SQL
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
Emp emp = new Emp();
emp.setId(resultSet.getInt("id"));
emp.setUsername(resultSet.getString("username"));
System.out.println(emp);
}
}
}
2、Mybatis方式
package com.kdy.tests;
import com.kdy.mapper.EmpMapper;
import com.kdy.pojo.Emp;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest {
SqlSession sqlSession;
@Test
public void test01() throws IOException {
//根据XML构建成sqlSessionFactory
String config = "mybatis.config.xml";
//将XML构建成输入流
InputStream inputStream= Resources.getResourceAsStream(config);
//建成sqlSessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
/*
*
* 可以设置事务为自动提交 ,因为执行 增删改的时候需要手动提交事务
* SqlSession openSession(boolean autoCommit);
SqlSession openSession(Connection connection);
SqlSession openSession(TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType);
SqlSession openSession(ExecutorType execType, boolean autoCommit);
SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType, Connection connection);
*
*
*
*
* */
sqlSession = sessionFactory.openSession();
Object o = sqlSession.selectOne("com.kdy.mapper.EmpMapper.selectEmp", 1);
System.out.println(o);
//Mybatis 在getMapper时就会给创建JDK动态代理
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
System.out.println(mapper.getClass());
System.out.println(mapper);
Emp emp = mapper.selectEmp(1);
System.out.println(emp);
}
}