• MyBatis的demo


    把以前写的关于mybatis的demo放在这边,以便查看。

    目录结构:  

     

     1 package com.test.mybatis.util;
     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 
    11 /**
    12  * 数据库连接工具类(MyBatis框架相关)
    13  * 
    14  * @author Wei
    15  * @time 2016年11月6日 下午5:08:33
    16  */
    17 public class UtilDBbyMyBatis {
    18     public static SqlSession sqlsssion;
    19 
    20     /**
    21      * 获取SqlSession
    22      * 
    23      * @return
    24      * @throws IOException
    25      */
    26     public static SqlSession GetSqlSession() throws IOException {
    27         if (null != sqlsssion) {
    28             return sqlsssion;
    29         } else {
    30             //Resources.getResourcesAsStream("xxx");这个是以src为根目录的
    31             InputStream ips = Resources.getResourceAsStream("com/test/mybatis/config/Configuration.xml");
    32             // 获取SqlSessionFactory
    33             SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(ips);
    34             sqlsssion = factory.openSession();
    35             return sqlsssion;
    36         }
    37 
    38     }
    39 }
    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     </mappers>
    45 
    46 </configuration>

    MyUser.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- Copyright 2009-2016 the original author or authors. Licensed under the 
        Apache License, Version 2.0 (the "License"); you may not use this file except 
        in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
        Unless required by applicable law or agreed to in writing, software distributed 
        under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 
        OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
        the specific language governing permissions and limitations under the License. -->
    <!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="MyUser22">
        <!-- 配置返回结果所属类 -->
        <resultMap type="com.test.mybatis.entity.MyUser" id="UserResult">
            <!-- 在数据库里如果是主键,那么就用<id>标签,其他字段用<column>标签 ,
                这里的type对应着java代码中的例如: java.sql.Types.BOOLEAN -->
            <id column="id" jdbcType="INTEGER" property="id" />
            <!-- column的值对应的是数据库里的字段名,property对应着实体类的属性 -->
            <result column="username" jdbcType="VARCHAR" property="username" />
            <!-- <result column="password" jdbcType="VARCHAR" property="password.encrypted" /> -->
            <result column="administrator" jdbcType="VARCHAR" property="administrator" />
        </resultMap>
        <!--Java代码使用示例: SqlSession.selectList("queryMyUserList_wyl"); -->
        <select id="queryMyUserList_wyl" resultMap="UserResult">
            SELECT * FROM MyUser
            WHERE 1=1
        </select>
        
        <select id="queryMyUserListbyName_wyl" parameterType="com.test.mybatis.entity.MyUser" resultMap="UserResult">
            SELECT ID,USERNAME,PASSWORD,ADMINISTRATOR FROM MyUser
            WHERE 1=1 
            <!-- <if test="username !=null and !&quot;&quot;.equals(username.trim())"> -->
            <if test="username !=null ">
                and USERNAME like '%'||#{username}||'%' 
            </if>
        </select>
        
        
        <!--同一个Mapper文件下, 不能有重复的id -->
        <!-- <select id="queryMyUserList_wyl" resultMap="UserResult"> SELECT * FROM 
            MyUser WHERE 1=1 </select> -->
    
        <select id="find" parameterType="long" resultMap="UserResult">
            SELECT * FROM
            MyUser WHERE id = #{id:INTEGER}
        </select>
        <delete id="deleteOne" parameterType="int">
            <!-- where 条件携程 #{_parameter}的形式具体 详见:http://www.imooc.com/video/4350, -->
            delete from MyUser where ID = #{_parameter}
        </delete>
        
        <!-- 批量删除 -->
        <delete id="deleteBatch" parameterType="java.util.List">
            delete from MyUser where id in (
                <!-- 用逗号隔开item属性值代表list集合中的每一项 -->
                <foreach collection="list" item="theitem"  >
                    ${theitem}
                </foreach>
            )
        </delete>
    </mapper>

    MyUser.java:

     1 package com.test.mybatis.entity;
     2 
     3 public class MyUser {
     4     private Long id;
     5 
     6     /*
     7      * user specified user ID
     8      */
     9     private String username;
    10 
    11     /*
    12      * encrypted password
    13      */
    14     private EncryptedString password;
    15 
    16     String administrator;
    17 
    18     public MyUser() {
    19         setUsername(new String());
    20         setPassword(new EncryptedString());
    21         setAdministrator("我是admin");
    22     }
    23 
    24     public Long getId() {
    25         return id;
    26     }
    27 
    28     public void setId(Long id) {
    29         this.id = id;
    30     }
    31 
    32     public String getUsername() {
    33         return username;
    34     }
    35 
    36     public void setUsername(String username) {
    37         this.username = username;
    38     }
    39 
    40     public EncryptedString getPassword() {
    41         return password;
    42     }
    43 
    44     public void setPassword(EncryptedString password) {
    45         this.password = password;
    46     }
    47 
    48     public String getAdministrator() {
    49         return administrator;
    50     }
    51 
    52     public void setAdministrator(String administrator) {
    53         this.administrator = administrator;
    54     }
    55 
    56 
    57 }
    MyBatisDemo01.java
     1 package com.test.mybatis.mybatistest;
     2 
     3 import java.io.IOException;
     4 import java.util.ArrayList;
     5 import java.util.List;
     6 
     7 import org.apache.ibatis.session.SqlSession;
     8 import org.apache.log4j.Logger;
     9 
    10 import com.test.mybatis.entity.EncryptedString;
    11 import com.test.mybatis.entity.MyUser;
    12 import com.test.mybatis.service.MaintainService;
    13 import com.test.mybatis.util.UtilDBbyMyBatis;
    14 
    15 /**
    16  * MyBatis测试类
    17  * 
    18  * @author Wei
    19  * @time 2016年11月6日 下午5:13:18
    20  */
    21 public class MyBatisDemo01 {
    22     public static void main(String[] args) throws IOException {
    23         
    24         SqlSession sqlSession = UtilDBbyMyBatis.GetSqlSession();
    25         /*
    26          * SqlSession.selectList(String str);里的str是根据实体类映射文件里的id来寻找的,
    27          * 实际上框架内部是通过"命名空间.str"的形式来查找对应的sql语句的(这个命名空间就是
    28          * 映射文件的namespace的值,具体到这个例子中就是<mapper namespace="MyUser22">),比如
    29          * sqlSession.selectList("queryMyUserList_wyl");这行代码,框架内部是根据
    30          * sqlSession.selectList("MyUser22.queryMyUserList_wyl");来寻找的,
    31          */
    32         List<MyUser> list = sqlSession.selectList("queryMyUserList_wyl");
    33         
    34         int len = list.size();
    35         for (int i = 0; i < len; i++) {
    36             System.out.println(list.get(i).getUsername() + ",id=" + list.get(i).getId());
    37         }
    38         System.out.println("==============分割线==============");
    39         MyUser user = new MyUser();
    40         user.setUsername("weiyongle359");
    41         user.setAdministrator("hr");
    42 //        user.setId(new Long(359));
    43         user.setPassword(new EncryptedString());
    44         System.out.println("==111111111111111111============分割线==============");
    45         Logger log = Logger.getRootLogger();
    46 //        log.debug("");
    47 //        log.info("");
    48 //        log.warn("xxxx");
    49 //        log.error("");
    50         List<MyUser> list2 = sqlSession.selectList("queryMyUserListbyName_wyl",user);
    51         System.out.println("==22222222222222222============分割线==============");
    52         int len2 = list2.size();
    53         for (int i = 0; i < len2; i++) {
    54             System.out.println(list2.get(i).getUsername() + ",id=" + list2.get(i).getId());
    55         }
    56         
    57         System.out.println("测试删除");
    58         int num = new MaintainService().delete("358");
    59         System.out.println("删除了"+num+"条数据");
    60         
    61         System.out.println("测试批量删除");
    62         List<String> idlist = new ArrayList<String>();
    63         idlist.add("342");
    64         idlist.add("356");
    65         idlist.add("357");
    66         int num2 = new MaintainService().deleteBatch(idlist);
    67     }
    68 }

    Oracle的建表语句:

     1 --select * from MyUser for update;
     2 
     3 --建表语句
     4 create table MyUser (
     5 id number,
     6 username varchar2(32) not null,
     7 password varchar2(128) not null,
     8 administrator varchar2(5),
     9 primary key (id)
    10 );
    11 
    12 --插入数据
    13 insert into MyUser
    14   (ID, USERNAME, PASSWORD, ADMINISTRATOR)
    15 values
    16   (BXGX_SEQ_AAZ611.Nextval,
    17    'weiyongle' || BXGX_SEQ_AAZ611.Nextval,
    18    'hr',
    19    'hr');
  • 相关阅读:
    jquery validate --转载
    领域驱动设计之领域模型--转载
    为system对象添加扩展方法
    DDD开源框架
    浅谈命令查询职责分离(CQRS)模式---转载
    AutoMapper小结
    执行后台任务的利器——Hangfire
    单元测试框架
    内存中的堆和栈
    ++*p,(*p)++,*p++与*++p四者的区别
  • 原文地址:https://www.cnblogs.com/Sunnor/p/6551443.html
走看看 - 开发者的网上家园