Mybatis-環境搭建
阿新 • • 發佈:2022-03-13
一、匯入座標
<!--mybatis 座標 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!--mysql 驅動座標 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> <scope>runtime</scope> </dependency>
二、編寫UserMapper對映檔案
<?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="userMapper"> <select id="findAll" resultType="com.finnlee.pojo.User"> select * from user </select> </mapper>
三、編寫MyBatis核心檔案
<?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"> <configuration> <environments default="develop"> <environment id="develop"> <transactionManager type="jdbc"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/demo?characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/finnlee/mapper/UserMapper.xml"/> </mappers> </configuration>
四、測試程式碼
// 載入核心配置檔案 InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml"); // 獲得 sqlSession 工廠物件 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); // 獲得 sqlSession 物件 SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> userList = sqlSession.selectList("userMapper.findAll"); System.out.println(userList); //關閉資源 sqlSession.close();