很多互联网公司放弃使用Hibernate, 改用MyBatis; 理由是MyBatis比较轻巧, 可以做SQL语句优化。PS: 想想DBA的工作吧, 大数量级的数据库操作需要专业的DBA做SQL语句优化。 Hibernate封装比较完善,导致它不够灵活。 我们需要的是减化数据库操作的编码量,对JDBC进行必要的封装即可。
Hibernate和Mybatis都提供了缓存功能, 但实际项目开发中更多的是使用中间件如Redis来做缓存;Mybatis最大的优势是在Java代码里生成复杂的SQL语句,Hibernate做不到。
MyBatis官方说明: http://www.mybatis.org/mybatis-3/zh/statement-builders.html
百度百科上的介绍:https://baike.baidu.com/item/MyBatis/2824918?fr=aladdin
项目结构:
在pom.xml中添加junit,mybatis和log4j的maven仓库:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.brycegao.mybatis</groupId>
<artifactId>mybatis_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
log4j默认会读取名为log4j.properties的文件。
MyBatis是对JDBC的封装,建议不要用MyBatis创建表。 我先电脑上启动MySQL服务, 并创建一个名为mybatis