mybatis-3.2版本,jdk1.6版本,Oracle数据库
1). 实现实体的增加、删除、修改、查询等基本需求,其中查询要求有返回多条记录的;
2). 数据库Oracle,插入时要求实现自增长主键的功能(从SEQUENCE中取值);
3). 要求插入后能够查询到新加的实体的主键值。
src\com\clzhang\sample\struts2\mapper MemberUserMapper.java mybatis的mapper处理类 src\com\clzhang\sample\struts2\mapper\entity MemberUserBean.java mybatis的entity类 src\com\clzhang\sample\struts2\test MyBatisTest.java 测试类,最终应该是在service的package中调用mapper中的方法。 resources\config mybatis-config.xml mybatis的配置文件 jdbc.properties JDBC连接配置文件
resources\com\clzhang\sample\struts2\mapper MemberUserMapper.xml mybatis的mapper配置文件
这里数据库为Oracle,表名为:MEMBER_USER,序列名:SEQ_MEMBER_USER,数据结构如下(假设已经存在测试数据):
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;
package com.clzhang.sample.struts2.mapper.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; } }
package com.clzhang.sample.struts2.mapper; import java.util.*; import com.clzhang.sample.struts2.mapper.entity.MemberUserBean; /** * 一个简单的CRUD操作示范类 * @author Administrator * */ public interface MemberUserMapper { public void insertUser(MemberUserBean user); public void updateUser(MemberUserBean user); public void deleteUser(int id); public MemberUserBean getUser(int id); public Map<String, Object> getUserHashMap(int id); public List<MemberUserBean> getUsersByAge(int startAge, int endAge); }
#main database settings jdbc.driver=oracle.jdbc.driver.OracleDriver jdbc.url=jdbc:oracle:thin:@192.168.2.136:1521:jingdu jdbc.username=jingdu jdbc.password=jingdu
<?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> <properties resource="config/jdbc.properties"> <!--username 和 password 将会由 properties 元素中设置的值来替换--> <property name="username" value="mytest"/> <property name="password" value="yourpass"/> </properties> <settings> <!--这些是极其重要的调整, 它们会修改 MyBatis 在运行时的行为方式。--> <setting name="cacheEnabled" value="false"/> <setting name="useGeneratedKeys" value="false"/> <setting name="defaultExecutorType" value="SIMPLE"/> <setting name="jdbcTypeForNull" value="OTHER"/> </settings> <typeAliases> <!-- 类型别名是为 Java 类型命名一个短的名字。它只和 XML 配置有关, 只用来减少类完全限定名的多余部分。 You can also specify a package where MyBatis will search for beans. For example <typeAliases> <package name="domain.blog"/> </typeAliases> ...... --> <typeAlias alias="MemberUser" type="com.clzhang.sample.struts2.mapper.entity.MemberUserBean"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <!-- 在 MyBatis 中有两种事务管理器类型(也就是 type=”[JDBC|MANAGED]”) <transactionManager type="MANAGED"> <property name="closeConnection" value="false"/> </transactionManager> NOTE If you are planning to use MyBatis with Spring there is no need to configure any TransactionManager because the Spring module will set its own one overriding any previously set configuration. --> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- <property name="poolMaximumActiveConnections " value="10"/> ...... --> </dataSource> </environment> </environments> <mappers> <mapper resource="com/clzhang/sample/struts2/mapper/MemberUserMapper.xml" /> <!--其它装载方式 <mapper url="file:///var/mappers/AuthorMapper.xml"/> <mapper class="org.mybatis.builder.BlogMapper"/> --> </mappers> </configuration>
<?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.sample.struts2.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>
package com.clzhang.sample.struts2.test; import java.io.*; 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.sample.struts2.mapper.MemberUserMapper; import com.clzhang.sample.struts2.mapper.entity.MemberUserBean; /** * mybatis的测试类,真正的应用,应该在service包中调用。 * * @author Administrator * */ public class MyBatisTest { 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 testInsert() { // SqlSession 的实例不能被共享,也是线程不安全的。因此最佳的范围是请求或方法范围。 SqlSession sqlSession = getSqlSessionFactory().openSession(); try { // 从技术上来说,当被请求时,任意映射器实例的最宽范围和 SqlSession 是相同的。最佳范围是方法范围。 MemberUserMapper mapper = sqlSession .getMapper(MemberUserMapper.class); MemberUserBean memberUser = new MemberUserBean(); memberUser.setName("张三"); memberUser.setPersonMobile("18662021536"); memberUser.setAddress("北京丰台某公司"); memberUser.setAge((int)Math.round(50 * Math.random())); 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(1); memberUser.setName(memberUser.getName() + "123"); memberUser.setPersonMobile(memberUser.getPersonMobile() + "456"); memberUser.setAddress(memberUser.getAddress() + "789"); memberUser.setAge(memberUser.getAge() + 10); mapper.updateUser(memberUser); sqlSession.commit(); } finally { sqlSession.close(); } } // @Test public void testDelete() { SqlSession sqlSession = getSqlSessionFactory().openSession(); try { MemberUserMapper mapper = sqlSession .getMapper(MemberUserMapper.class); 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(3); System.out.println("name:" + memberUser.getName() + "\tmobile:" + memberUser.getPersonMobile() + "\taddress:" + memberUser.getAddress() + "\tage=" + memberUser.getAge()); } finally { sqlSession.close(); } System.out.println("-------------------------------"); } // @Test public void getUserHashMap() { SqlSession sqlSession = getSqlSessionFactory().openSession(); try { MemberUserMapper mapper = sqlSession .getMapper(MemberUserMapper.class); Map<String, Object> map = mapper.getUserHashMap(3); Iterator<String> iterator = map.keySet().iterator(); while(iterator.hasNext()){ String columnName = iterator.next(); // value没有转换是因为value可能是各种值 System.out.println(columnName + "=" + map.get(columnName)); } } finally { sqlSession.close(); } System.out.println("-------------------------------"); } @Test public void getUserByAge() { SqlSession sqlSession = getSqlSessionFactory().openSession(); try { MemberUserMapper mapper = sqlSession .getMapper(MemberUserMapper.class); List<MemberUserBean> list = mapper.getUsersByAge(20, 30); for(MemberUserBean memberUser: list) { System.out.println("name:" + memberUser.getName() + "\tmobile:" + memberUser.getPersonMobile() + "\taddress:" + memberUser.getAddress() + "\tage=" + memberUser.getAge()); } } finally { sqlSession.close(); } System.out.println("-------------------------------"); } }
测试输出(部分):
name:蔡亚春 mobile:13401786668 address:null age=26
name:张志伟 mobile:13401786668 address:null age=29