1、引入依赖jar
mysql-connector-java
mybatis
mysql
mysql-connector-java
5.1.39
org.mybatis
mybatis
3.4.1
2、配置mybatis的全局配置文件mybatis-config.xml
需求:查询test库中Student表,通过ID查询用户信息
select * from Student where SID = 1;
3、创建Student.java自定义对象
创建SutdentMapper.java接口文件
创建StudentMapper.xml配置文件
SutdentMapper.java接口文件
public interface StudentMapper {
public Student getStudentByID(int id);
}
StudentMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?><!--
select:查询操作标签
id属性:相当于jdbc中的Statement,指定接口中方法
parameterType:指定入参类型
resultType:指定返回参数类型 对应类型的全路径名
#{id}:占位符
-->
<select id="getStudentByID" parameterType="java.lang.Integer" resultType="com.tulun.bean6.Student">
select * from Student where SID = #{id};
</select>
4\在全局配置文件中mybatis-config.xml
5、接口方法调用
String resource = “mybatis-config.xml”;
//读取配置文件
InputStream asStream = Resources.getResourceAsStream(resource);
//创建SQLSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(asStream);
//创建SQLSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//产生代理类执行方法
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = mapper.getStudentByID(1);