java mybatis 使用步骤
1. Pom 文件依赖
<?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>cn.monkey</groupId> <artifactId>java_mybatis_01</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> </project>
2.1 sql 配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--mybatis 的主配置文件--> <configuration> <environments default="mysql"> <!--mysql配置--> <environment id="mysql"> <!--配置事务类型--> <transactionManager type="JDBC"></transactionManager> <!--配置数据源(连接池)--> <dataSource type="POOLED"> <!--配置连接数据库的4要素--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="cn/monkey/dao/UserDao.xml"></mapper> </mappers> </configuration>
2.2 mapper 配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.monkey.dao.UserDao"> <select id="findAll" resultType="cn.monkey.domain.User"> SELECT * FROM USER </select> </mapper>
3. 创建 javaBean 和 Dao 层的 interface
4. 调用 java api 调用
public void test1 () throws IOException { // 1. 读取配置文件 InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml"); // 2. 创建 SqlSessionFactory 工厂 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(is); // 3. 使用工厂类创建 SqlSesson 对象 SqlSession session = factory.openSession(); // 4. 使用 sqlSession 对象创建 Dao 层的代理对象 UserDao userDao = session.getMapper(UserDao.class); // 5. 使用代理对象执行方法 List<User> users = userDao.findAll(); for (User user : users) { System.out.println(user); } // 6. 释放资源 session.close(); is.close(); }