入门程序
-
创建maven程序
-
导入MyBatis依赖。pom.xml下导入如下依赖
<dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.23</version></dependency>
</dependencies>
- resources文件下创建ApplicationContext.xml文件并且导入如下代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/test"/> // 导入自己的数据库路径<property name="username" value="***"/> // 输入自己的数据库账号<property name="password" value="***"/> // 输入自己的数据库密码</dataSource></environment></environments>
</configuration>
- 创建表结构
- resources文件下创建CarMapper.xml并且加入如下代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="name"><select id="saveCar" >insert into car(car_num, brand, guide_price, produce_time, car_type)values ('102', '大奔', 100, '2020-01-01', 'suv')</select>
</mapper>
- 在ApplicationContext.xml文件下加入如下代码
<mappers><mapper resource="CarMapper.xml"/>
</mappers>
- 主文件下加入如下代码并且执行
SqlSession sqlSession=null;try {SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();SqlSessionFactory sqlSessionFactory= sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("ApplicationContext.xml"));sqlSession=sqlSessionFactory.openSession();sqlSession.insert("saveCar");sqlSession.commit();}catch (IOException e){if(sqlSession!=null){sqlSession.rollback();}e.printStackTrace();}finally {if (sqlSession != null) {sqlSession.close();}}
入门程序的细节
- MyBatis中的sql语句结尾可以不加;号。
- resource这类单词一般从类的根路径下加载,url一般从绝对路径下加载资源
- MyBatis的配置文件名可以不固定,也可以不固定位置。但是为了可移植性最好放在resource下
MyBatis的事务管理机制
ApplicationContext文件中的< transactionManager/>标签的type属性支持两个值
- type=“JDBC”:MyBatis自己管理事务,采用原生jdbc去管理事务
- type=“MANAGED”:MyBatis放弃管理事务,事务管理交给其他容器
开发依赖
引入junit单元测试
pom.xml加入如下依赖
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope>
</dependency>
集成logback日志框架
ApplicationContext.xml加入如下代码
<settings><setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
Sql工具类封装
创建utiles/SqlSession.class类,并加入如下代码
public class SqlSessionUtil {private SqlSessionUtil() {}private static SqlSessionFactory sqlSessionFactory;static {try {SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("ApplicationContext.xml"));} catch (Exception e) {e.printStackTrace();}}public static SqlSession createSqlSession() {return sqlSessionFactory.openSession();}}