首先在iml文件中java
<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.26</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> </dependencies>
在java目錄中建立一個domain實現類User,實現Serializable接口mysql
public class User implements Serializable { private Integer id; private String username; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; }
在rescources文件中建立SqlMapConfig.xml文件web
<?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="mysql"> <!-- 配置mysql環境--> <environment id="mysql"> <!-- 配置事務--> <transactionManager type="JDBC"></transactionManager> <!-- 配置鏈接池--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/javaweb1"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!-- 配置映射文件的位置--> <mappers> <mapper resource="dao/IUserDao.xml"></mapper> </mappers> </configuration>
在resources中建造一個dao文件再IUserDao.xmlsql
<?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"> <!--namespace肯定方法在哪一個Dao接口,id指的是哪一個方法,resultType封裝至哪--> <mapper namespace="dao.IUserDao"> <!-- 查詢全部操做--> <select id="findAll" resultType="dao.IUserDao"> select * from web1; </select> </mapper>
編寫持久層接口IUserDaosession
public interface IUserDao { /** * @return */ List<User> findAll(); }
編寫測試類mybatis
public class MybatisTest { /* 測試查詢全部 */ @Test public void testFindall() throws Exception{ //1.讀取配置文件,生成字節輸入流 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.獲取SqlSessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //3.獲取sqlsession對象 SqlSession sqlSession = factory.openSession(); //4.獲取dao的代理對象 IUserDao userDao = sqlSession.getMapper(IUserDao.class); //5執行查詢全部方法 List<User> users = userDao.findAll(); for (User user:users){ System.out.println(user); } //釋放資源 sqlSession.close(); in.close(); } }