MyBatis的接口式编程Demo

  

 很久没细看过MyBatis了,时间一长就容易忘记。

下面是一个接口式编程的例子。

这里的例子一共分为4步:

1 首先要有一个namespace为接口的全类名的映射文件,该例中是 IMyUser.xml
2 然后在mybatis的容器(就是总的配置文件)里的mappers标签内
引入第1步中的映射文件,这里是 IMyUser.xml
3 通过SqlSession对象的getMapper(IMyUserDao.class)
获取一个接口的代理对象
4 调用代理对象的具体方法,也就是对应着 IMyUser.xml中的各个select,insert
等标签,这些标签的id属性同时必须与接口中的方法名一一对应

 所需要的数据库表:

 1 -- Create table
 2 create table MYUSER
 3 (
 4   id            NUMBER not null,
 5   username      VARCHAR2(32) not null,
 6   password      VARCHAR2(128) not null,
 7   administrator VARCHAR2(5) not null
 8 );
 9 
10 
11 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
12 values ('1', 'weiyongle01', 'hr', 'hr');
13 
14 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
15 values ('352', 'weiyongle352', 'hr', 'hr');
16 
17 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
18 values ('353', 'weiyongle353', 'hr', 'hr');
19 
20 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
21 values ('354', '1', 'hr', 'hr');
22 
23 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
24 values ('355', 'weiyongle355', 'hr', 'hr');
25 
26 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
27 values ('359', 'weiyongle359', 'hr', 'hr');
28 
29 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
30 values ('360', 'weiyongle360', 'hr', 'wyl');
31 
32 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
33 values ('361', 'weiyongle361', 'hr', 'hr');
34 
35 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
36 values ('362', 'weiyongle362', 'hr', 'hr');
37 
38 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
39 values ('363', 'weiyongle363', 'hr', 'hr');
40 
41 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
42 values ('364', 'weiyongle364', 'hr', 'hr');
43 
44 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
45 values ('365', 'weiyongle365', 'hr', 'hr');
46 
47 insert into myuser (ID, USERNAME, PASSWORD, ADMINISTRATOR)
48 values ('390', 'weiyongle359', 'hr', 'hr');

 

1 MyBatis配置文件,Configuration.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!-- Copyright 2009-2016 the original author or authors. Licensed under the 
 3     Apache License, Version 2.0 (the "License"); you may not use this file except 
 4     in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 5     Unless required by applicable law or agreed to in writing, software distributed 
 6     under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 
 7     OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
 8     the specific language governing permissions and limitations under the License. -->
 9 <!DOCTYPE configuration
10     PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
11     "http://mybatis.org/dtd/mybatis-3-config.dtd">
12 
13 <configuration>
14     <settings>
15         <setting name="useGeneratedKeys" value="false" />
16         <setting name="useColumnLabel" value="true" />
17     </settings>
18 
19     <!-- <typeAliases> <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/> 
20         </typeAliases> -->
21 
22     <environments default="development">
23         <environment id="development">
24             <transactionManager type="JDBC">
25                 <property name="" value="" />
26             </transactionManager>
27             <dataSource type="UNPOOLED">
28                 <!-- Oracle数据库配置 -->
29                 <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
30                 <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl2" />
31                 <property name="username" value="hr" />
32                 <property name="password" value="hr" />
33             </dataSource>
34         </environment>
35     </environments>
36 
37     <!-- 配置的实体类 20161106添加 -->
38     <mappers>
39         <!-- <mapper resource="org/apache/ibatis/submitted/complex_property/User.xml" /> -->
40         <!-- 这个路径是从src下开始的,即以src作为根目录的,
41             这点和Resources.getResourcesAsStream("xx")里的xx一样,都是指向的具体文件的路径
42             ,都是以src为根目录 -->
43         <mapper resource="com/test/mybatis/config/MyUser.xml" />
44         <!-- 接口式编程 -->
45         <!-- <mapper class="com.test.mybatis.dao.interf.IMyUserDao"/> -->
46         <mapper resource="com/test/mybatis/config/IMyUser.xml" />
47     </mappers>
48 
49 </configuration>

2 IMyUser.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!-- Copyright 2009-2016 the original author or authors. Licensed under the 
 3     Apache License, Version 2.0 (the "License"); you may not use this file except 
 4     in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 5     Unless required by applicable law or agreed to in writing, software distributed 
 6     under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 
 7     OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
 8     the specific language governing permissions and limitations under the License. -->
 9 <!DOCTYPE mapper
10     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
11     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
12 <!-- MyBatis接口式编程 -->
13 <!-- 这里的namespace一定要是接口的全类名,这样就能够保证该mapper的唯一性 -->
14 <mapper namespace="com.test.mybatis.dao.interf.IMyUserDao">
15     <!-- select标签里的id属性值 getUser 对应着 上面namespace里的方法,
16         实际上就是接口里定义的方法 -->
17     <select id="getUser"  resultType="com.test.mybatis.entity.MyUser" parameterType="int">
18         select * from MyUser where id = #{id}
19     </select>
20     <!-- select标签里的id属性值 getUserbyUser 对应着 上面namespace里的方法,
21         实际上就是接口里定义的方法 -->
22     <select id="getUserbyUser"  parameterType="com.test.mybatis.entity.MyUser" resultType="com.test.mybatis.entity.MyUser" >
23         select * from MyUser 
24         where 1=1 
25         <!-- if 标签里的 test的属性值 username实际上是指的是
26          parameterType的属性值  com.test.mybatis.entity.MyUser 
27          这个类里的一个成员属性,用于getter和setter方法,
28          不是之前理解的对应于数据库里的字段,还有username !='' 
29            一定要写上,如果不写的话那么这个String类型的username成员变量
30          就会被MyBatis框架默认为"",从而可能会影响这里配置的slq的逻辑,
31          从而查询出来的结果可能会与我们自己设想中的不一样 -->
32         <if test="username != null and username !='' ">
33             AND username = #{username}
34           </if>
35           <if test="administrator != null and username !='' ">
36             AND administrator = #{administrator}
37           </if>
38     </select>
39     
40     <delete id="deleteUser" parameterType="String">
41         delete from MyUser where id = #{id}
42     </delete>
43 </mapper>

 

3.IMyUserDao.java

 1 package com.test.mybatis.dao.interf;
 2 
 3 import com.test.mybatis.entity.MyUser;
 4 
 5 /**
 6  * MyBatis接口式编程Demo
 7  * @author Wei
 8  * @time  2017年3月23日 下午1:26:21
 9  */
10 public interface IMyUserDao {
11     public MyUser getUser(int id);
12     public MyUser getUserbyUser(MyUser user);
13     public void deleteUser(String username);
14 }

4. IMyUserTest.java

 1 package com.test.mybatis.dao.interf;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10 import com.test.mybatis.entity.MyUser;
11 
12 /**
13  * 接口式编程的测试类
14  * @author Wei
15  * @time  2017年3月23日 下午2:26:22
16  */
17 public class IMyUserTest {
18 
19     public IMyUserTest() {
20         // TODO Auto-generated constructor stub
21     }
22     
23     public static void main(String[] args) {
24         InputStream is = null;
25         SqlSessionFactory factory = null;
26         SqlSession sqlsession = null;
27         try {
28             is = Resources.getResourceAsStream("com/test/mybatis/config/Configuration.xml");
29             factory = new SqlSessionFactoryBuilder().build(is);
30             sqlsession = factory.openSession();
31             /**
32              * 获取接口,实际上是通过代理模式来获取的代理对象
33              * 1 首先要有一个namespace为接口的全类名的映射文件,该例中是 IMyUser.xml
34              * 2 然后在mybatis的容器(就是总的配置文件)里的mappers标签内
35              * 引入第1步中的映射文件,这里是 IMyUser.xml
36              * 3 通过SqlSession对象的getMapper(IMyUserDao.class)
37              * 获取一个接口的代理对象
38              * 4 调用代理对象的具体方法,也就是对应着 IMyUser.xml中的各个select,insert
39              * 等标签,这些标签的id属性同时必须与接口中的方法名一一对应
40              */
41             IMyUserDao dao = sqlsession.getMapper(IMyUserDao.class);
42             MyUser user = new MyUser();
43             user.setUsername("weiyongle363");
44 //            user.setAdministrator("wyl");
45             //调用接口的方法
46             user = dao.getUserbyUser(user);//正常
47 //            user = dao.getUser(361);//正常运行
48 //            user = dao.getUser(355);
49 //            MyUser user = sqlsession.selectOne("com.test.mybatis.dao.interf.IMyUserDao.getUser",1);
50             if(user!=null){
51                 System.out.println(user.toString());
52             }else{
53                 System.out.println("没有查询到结果");
54             }
55             
56         } catch (IOException e) {
57             // TODO Auto-generated catch block
58             e.printStackTrace();
59         }
60     }
61 }

 执行结果:

 

posted @ 2017-03-23 14:58  Sunor  阅读(2638)  评论(0编辑  收藏  举报