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‘);
时间: 2024-10-01 04:44:23

MyBatis的demo的相关文章

MyBatis使用DEMO及cache的使用心得

下面是一个简单的MyBatis使用DEMO. 整体结构 整体代码大致如下: POM依赖 需要引用两个jar包,一个是mybatis,另一个是mysql-connector-java,如果是maven工程的话,pom里如下添加依赖就可以了. <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.3</ver

SpringMVC+Spring+Mybatis(SSM~Demo) 【转】

SpringMVC+Spring+Mybatis 框架搭建 整个Demo的视图结构: JAR: 下载地址:http://download.csdn.net/detail/li1669852599/8546059 首先,我是使用MyEclipse工具做的这个例子,整合了Sping 3 .Spring MVC 3 .MyBatis框架,演示数据库采用MySQL数据库.例子中主要操作包括对数据的添加(C).查找(R).更新(U).删除(D).我在这里采用的数据库连接池是来自阿里巴巴的Druid,至于D

Mybatis入门DEMO

下面将通过以下步骤说明如何使用MyBatis开发一个简单的DEMO: 步骤一:新建表STUDENTS 字段有: Stu_Id.Stu_Name.Stu_Age.Stu_Birthday 1 CREATE TABLE `student` ( 2 `Stu_Id` bigint(20) NOT NULL AUTO_INCREMENT , 3 `Stu_Name` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL , 4

最基础的mybatis入门demo

demo结构 数据库情况 (不会转sql语句 骚瑞) 数据库连接信息 jdbc.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mysql_demo jdbc.username=root jdbc.password=root javabean Student.class package entity; public class Student { private Integer i

SpringMVC+Spring+Mybatis(SSM~Demo)

SpringMVC+Spring+Mybatis 框架搭建 整个Demo的视图结构: JAR: 下载地址:http://download.csdn.net/detail/li1669852599/8546059 首先,我是使用MyEclipse工具做的这个例子,整合了Sping 3 .Spring MVC 3 .MyBatis框架,演示数据库采用MySQL数据库.例子中主要操作包括对数据的添加(C).查找(R).更新(U).删除(D).我在这里采用的数据库连接池是来自阿里巴巴的Druid,至于D

JAVA应用程序单独集成Mybatis使用Demo

参考博客:http://www.cnblogs.com/magialmoon/archive/2013/10/30/3397828.html 整体结构 POM依赖 <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.3</version> </dependency> <depen

Mybatis_reveiw之Mybatis官方的一个很简单的Demo

上学的时候,一个老师讲了个故事,这个故事的大意是,我们有很多种方式去削苹果,第一种方式,使用指甲刀,第二种方式,使用机床,第三种方式,使用手摇的那种削平果小工具.我们当然都能够完成这个简单的需求,但是使用指甲刀削出来的苹果一定比较坑坑洼洼,不够美观,而且可能会让人感觉到有点没啥食欲.使用机床呢?可能会造成大量的浪费,原本一个美观大方的苹果变成了只能啃几口的正方形.第三个,因为是专门为了削苹果皮而设计的,理论上是最合适用来解决削苹果这个问题的解决方案. 一个好的架构,其实要做的事情是非常简单的,除

深入浅出Mybatis系列(一)---Mybatis入门[转]

最近两年 springmvc + mybatis 的在这种搭配还是蛮火的,楼主我呢,也从来没真正去接触过mybatis, 趁近日得闲, 就去学习一下mybatis吧. 本次拟根据自己的学习进度,做一次关于mybatis 的一系列教程, 记录自己的学习历程, 同时也给还没接触过mybatis的朋友探一次道.本系列教程拟 由浅(使用)入深(分析mybatis源码实现),故可能需要好长几天才能更新完.好啦,下面就开始本次的mybatis 学习之旅啦, 本次为第一篇教程, 就先简单地写个demo, 一起

MyBatis学习笔记(一)

测试Demo的目录结构: com.luohao.config ->MyBatisCongfig.xml ->userMapper.xml com.luohao.Test ->TestMyBatis.class ->User.class 测试数据库是MySQL,用的数据库连接是JDBC,上面的目录结构中MyBatisConfig.xml是MyBatis的核心配置文件,userMapper.xml是用来映射SQL语句的,这里的映射使用了mxl文件来配置而没有使用注释的方式的原因是在很多