1.创建maven工程
Create New Project–>Maven–>勾选create from archetype–>maven archetype quickstart–>……
2.添加jar包坐标
在pom.xml中添加如下依赖包:
<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>
3.编写实体类
Mybitis使用了ORM(Object Relational Mappging 对象关系映射)思想,即要求数据库表字段和实体类属性相对应。假如数据库有一个User表为:
CREATE TABLE `user` ( `id` int(11) NOT NULL auto_increment, `username` varchar(32) NOT NULL COMMENT '用户名', `sex` char(1) default NULL COMMENT '性别', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`id`,`username`,`sex`) values (41,'老王','男'),(42,'二王','女');
需要创建的User类具有相同的数表字段名,同时需要实现Serializable接口,放在src/main/java下,代码如下:
package com.gqzzw.domain; import java.io.Serializable; public class User implements Serializable { private Integer id; private String userName; private String sex; 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 getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
4.编写实体类的持久层映射接口
这里对应的User类持久层映射接口取名UserMapper,放在src/main/java下,代码如下:
package com.gqzzw.mapper; import com.gqzzw.domain.User; import java.util.List; public interface UserMapper { //查询所有用户 List<User> findAll(); }
5.编写映射接口的配置文件
放在src/main/resources下,必须与久层接口包路径和文件名相同,即:com.gqzzw.mapper.UserMapper.xml
<?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="com.gqzzw.mapper.UserMapper"> <!-- 配置SQL语句 --> <select id="findAll" resultType="com.gqzzw.domain.User"> select * from user </select> </mapper>
6.编写MyBatis主配置文件
放在src/main/resources下,新建SqlMapConfig.xml,内容如下:
<?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="local"> <!-- 环境配置 --> <environment id="local"> <!-- 事务类型 --> <transactionManager type="JDBC"></transactionManager> <!-- 数据源(连接池) --> <dataSource type="POOLED"> <!-- 连接mysql四要素 --> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- 映射配置文件位置 --> <mappers> <mapper resource="com/gqzzw/dao/UserDao.xml"></mapper> </mappers> </configuration>
7.编写log4j的配置文件
放在src/main/resources下,新建log4j.properties,内容如下:
#设置日志的级别,输出目的 log4j.rootLogger=DEBUG, stdout #设置输出目的地为控制台 log4j.appender.stdout=org.apache.log4j.ConsoleAppender #布局为PatternLayout,可灵活地指定布局模式。 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout #设置输出格式 log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
8.编写测试类
放在src/test/java下,编写测试类,内容如下:
package com.gqzzw.mapper; import com.gqzzw.domain.User; import com.gqzzw.mapper.UserMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class UserMapperTset { @Test public void test() throws IOException { //1.读取配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建SqlSessionFactory的构建者对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //3.使用构建者创建工厂对象SqlSessionFactory SqlSessionFactory factory = builder.build(in); //4.使用SqlSessionFactory生产SqlSession对象 SqlSession sqlSession = factory.openSession(); //5.使用SqlSession创建映射接口的代理对象 UserMapper mapper = sqlSession.getMapper(UserMapper.class); //6.使用代理对象执行查询所有方法 List<User> users = mapper.findAll(); //7.遍历集合 for (User user : users) { System.out.println(user); } //8.释放资源 sqlSession.close(); in.close(); } }
9.使用Junit测试
测试结果类似如下代表成功:
DEBUG [main] - ==> Preparing: select * from user DEBUG [main] - ==> Parameters: DEBUG [main] - <== Total: 2 User{id=41, username='老王', sex=男} User{id=42, username='二王', sex=女}
10.使用注解(可选)
移除映射接口的配置文件UserMapper.xml,修改主配置文件的映射配置为:
<!-- 映射配置文件位置 --> <mappers> <mapper class="com.gqzzw.mapper.UserMapper"/> </mappers>
再在实体类映射接口UserMapper.class的方法上添加@Select注解:
package com.gqzzw.mapper; import com.gqzzw.domain.User; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper { //查询所有用户 @Select("select * from user") List<User> findAll(); }
转载请注明:零五宝典 » IDEA中Maven工程的MyBatis快速入门