一、环境
mybatis-3.2版本,jdk1.8版本,Oracle数据库
二、准备工作
1. 下载mybatis-3.2,需要引用其中的若干包
mybatis-3.2.0.jar lib/asm-3.3.1.jar lib/cglib-2.2.2.jar lib/commons-logging-1.1.1.jar lib/javassist-3.17.1-GA.jar lib/log4j-1.2.17.jar lib/slf4j-api-1.7.2.jar lib/slf4j-log4j12-1.7.2.jar
2 项目的目录结构
com.clzhang.mybatis.mapper MemberUserMapper.java MyBatis的mapper处理类 com.clzhang.mybatis.entity MemberUserBean.java MyBatis的entity类 com.clzhang.test MyBatisTest1.java 测试类,最终应该是在service的package中调用mapper中的方法。 resourcesconfig mybatis-config.xml MyBatis的配置文件 resourcescomclzhangmybatismapper MemberUserMapper.xml MyBatis的mapper配置文件
3.假定数据库已经创建,表结构也已经创建,并且有测试数据
CREATE TABLE MEMBER_USER ( ID NUMBER NOT NULL PRIMARY KEY, NAME VARCHAR2(30), PERSONMOBILE VARCHAR2(20), ADDRESS VARCHAR2(255), AGE NUMBER); CREATE SEQUENCE SEQ_MEMBER_USER;
三、具体步骤
1. 创建entity类
package com.clzhang.mybatis.entity; public class MemberUserBean { private int id; private String name; private String personMobile; private String address; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPersonMobile() { return personMobile; } public void setPersonMobile(String personMobile) { this.personMobile = personMobile; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
2. 创建mapper类
package com.clzhang.mybatis.mapper; import java.util.*; import com.clzhang.mybatis.entity.MemberUserBean; public interface MemberUserMapper { public void insertUser(MemberUserBean user); public void updateUser(MemberUserBean user); public void deleteUser(int id); public MemberUserBean getUser(int id); public HashMap getUserHashMap(int id); public List getUsersByAge(int startAge, int endAge); }
3. 创建mybatis-config.xml的配置文件,位置于resources/config目录
<?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> <settings> <setting name="cacheEnabled" value="false" /> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> </settings> <typeAliases> <typeAlias alias="MemberUser" type="com.clzhang.mybatis.entity.MemberUserBean"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/> <property name="username" value="mytest"/> <property name="password" value="test001"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/clzhang/mybatis/mapper/MemberUserMapper.xml" /> </mappers> </configuration>
4. 创建MemberUserMapper.xml配置文件,位置于:resourcescomclzhangmybatismapper
<?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.clzhang.mybatis.mapper.MemberUserMapper"> <!-- 默认情况下是没有开启缓存的,下条代码是开启二级缓存的,作用如下: 1.•映射语句文件中的所有 select 语句将会被缓存。 2.•映射语句文件中的所有 insert,update 和 delete 语句会刷新缓存。 3.•缓存会使用 Least Recently Used(LRU,最近最少使用的)算法来收回。 ...... --> <cache /> <!--以单个对象方式返回--> <select id="getUser" resultType="MemberUser" parameterType="int"> select ID, NAME, PERSONMOBILE, ADDRESS, AGE FROM MEMBER_USER WHERE ID = #{id} </select> <!--以HashMap方式返回单个实例,包含列名与值的映射--> <select id="getUserHashMap" resultType="hashmap" parameterType="int"> select ID, NAME, PERSONMOBILE, ADDRESS, AGE FROM MEMBER_USER WHERE ID = #{id} </select> <resultMap type="MemberUser" id="userAgeMap"> <id property="id" column="id"/> <!--有需要做数据库到实体类名称转换的,可以写在这里--> <!-- <result property="objname" column="dbname"/> --> </resultMap> <!--以List方式返回多个结果--> <!--参数名称目前不可以自行指定(无法与Mapper中保持一致),待查--> <select id="getUsersByAge" resultMap="userAgeMap" parameterType="int"> <![CDATA[ select ID, NAME, PERSONMOBILE, ADDRESS, AGE FROM MEMBER_USER WHERE AGE > #{param1} AND AGE < #{param2} ]]> </select> <!--Oracle的实现自增长主键的方式--> <insert id="insertUser" parameterType="MemberUser"> <selectKey keyProperty="id" resultType="int" order="BEFORE"> select SEQ_MEMBER_USER.nextval from DUAL </selectKey> INSERT INTO MEMBER_USER (ID, NAME, PERSONMOBILE, ADDRESS, AGE) VALUES(#{id}, #{name}, #{personMobile}, #{address}, #{age}) </insert> <update id="updateUser" parameterType="MemberUser"> update MEMBER_USER set NAME = #{name}, PERSONMOBILE = #{personMobile}, ADDRESS = #{address}, AGE = #{age} where id = #{id} </update> <delete id="deleteUser" parameterType="int"> delete from MEMBER_USER where ID = #{id} </delete> </mapper>
5. 创建测试类
package com.clzhang.test; import java.io.IOException; import java.io.Reader; import java.util.*; 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 com.clzhang.mybatis.mapper.MemberUserMapper; import com.clzhang.mybatis.entity.MemberUserBean; /** * mybatis的测试类,真正的应用,应该在service包中调用。 * @author Administrator * */ public class MyBatisTest1 { private static final String MYBATIS_CONFIG_FILENAME = "config/mybatis-config.xml"; private static SqlSessionFactory sqlSessionFactory; static { Reader reader = null; try { reader = Resources.getResourceAsReader(MYBATIS_CONFIG_FILENAME); } catch (IOException e) { System.out.println(e.getMessage()); } // 一旦你创建了 SqlSessionFactory 后,SqlSessionFactoryBuilder这个类就不需要存在了。 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } /** * SqlSessionFactory 应该在你的应用执行期间都存在。没有理由来处理或重新创建它。 * @return */ public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } // @Test public void testInert() { // SqlSession 的实例不能被共享,也是线程不安全的。因此最佳的范围是请求或方法范围。 SqlSession sqlSession = getSqlSessionFactory().openSession(); try { // 从技术上来说,当被请求时,任意映射器实例的最宽范围和 SqlSession 是相同的。最佳范围是方法范围。 MemberUserMapper mapper = sqlSession .getMapper(MemberUserMapper.class); MemberUserBean memberUser = new MemberUserBean(); // 因为ID为自增长字段,所以此处不需要设置 memberUser.setName("李勇"); memberUser.setPersonMobile("998877"); memberUser.setAddress("江苏某地方"); memberUser.setAge(38); mapper.insertUser(memberUser); sqlSession.commit(); // 查看新加的对象主键 System.out.println("新加对象的id:" + memberUser.getId()); } finally { sqlSession.close(); } } // @Test public void testUpdate() { SqlSession sqlSession = getSqlSessionFactory().openSession(); try { MemberUserMapper mapper = sqlSession .getMapper(MemberUserMapper.class); // 先查询,后更新 MemberUserBean memberUser = mapper.getUser(8); memberUser.setName("赵五副本"); memberUser.setPersonMobile("12345"); memberUser.setAddress("天津上地某公司"); memberUser.setAge(29); mapper.updateUser(memberUser); sqlSession.commit(); } finally { sqlSession.close(); } } // @Test public void testDelete() { SqlSession sqlSession = getSqlSessionFactory().openSession(); try { MemberUserMapper mapper = sqlSession.getMapper(MemberUserMapper.class); // 直接设置ID主键,然后删除 mapper.deleteUser(2); sqlSession.commit(); } finally { sqlSession.close(); } } // @Test public void getUser() { SqlSession sqlSession = getSqlSessionFactory().openSession(); try { MemberUserMapper mapper = sqlSession .getMapper(MemberUserMapper.class); MemberUserBean memberUser = mapper.getUser(5); System.out.println("name:" + memberUser.getName() + " mobile:" + memberUser.getPersonMobile() + " address:" + memberUser.getAddress()); } finally { sqlSession.close(); } } // @Test public void getUserHashMap() { SqlSession sqlSession = getSqlSessionFactory().openSession(); try { MemberUserMapper mapper = sqlSession .getMapper(MemberUserMapper.class); HashMap<String, Object> hashMap = mapper.getUserHashMap(5); for (Map.Entry<String, Object> entry : hashMap.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); System.out.println(key + ":" + value); } } finally { sqlSession.close(); } } @Test public void getUserByAge() { SqlSession sqlSession = getSqlSessionFactory().openSession(); try { MemberUserMapper mapper = sqlSession .getMapper(MemberUserMapper.class); List<MemberUserBean> myList = mapper.getUsersByAge(20, 40); for (MemberUserBean entry : myList) { int key = entry.getId(); String value = entry.getAddress(); System.out.println(key + ":" + value); } } finally { sqlSession.close(); } } }
四、单独测试各个模块
解除注释JUnit各单元,然后键盘输入:alt+shift+X,T,分别进行测试。