2024-07-11
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
A: MyBatis is a semi-automatic persistence layer framework that can write SQL statements through XML or annotations and map SQL statements to Java objects. MyBatis does not completely automatically generate SQL statements, but allows developers to manually write SQL, which provides greater flexibility and control.
Hibernate is a fully automatic ORM framework that can automatically generate SQL statements and provide more functions, but its configuration is relatively complex.
A: The execution process of MyBatis includes several main steps, from configuration initialization to executing SQL and returning results. The detailed process is as follows
// 1. 加载配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2. 创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 3. 创建SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
// 4. 获取Mapper
UserMapper mapper = session.getMapper(UserMapper.class);
// 5. 执行SQL
User user = mapper.selectUser(1);
// 6. 处理结果集
System.out.println(user);
// 7. 管理事务(如果需要)
session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 8. 关闭SqlSession
session.close();
}