mybatis使用步骤:
1、引入依赖
<!--数据源配置-->
<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/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
需求:通过ID查询Student表中用户信息
3、创建pojo类(提供基本的get和set方法)
/**
- 创建Pojo类,和数据库表Student对应
*/
public class Student {
private int SID;
private String Sname;
private String Ssex;
private int Sage;
省略get和set方法
}
4、创建StudentMapper.java接口文件
public interface StudentMapper {
// 需求:通过ID查询Student表中用户信息
//select * from Student where SID = XXX
public Student getStudentById(int sid);
}
5、创建StudentMapper.xml配置文件
//读取配置文件
InputStream asStream = Resources.getResourceAsStream(resource);
//创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(asStream);
//创建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//通过动态代理产生StudentMapper对象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = mapper.getStudentById(1);
System.out.println(student);