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

目录结构: 

 package com.test.mybatis.util;

 import java.io.IOException;
import java.io.InputStream; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; /**
* 数据库连接工具类(MyBatis框架相关)
*
* @author Wei
* @time 2016年11月6日 下午5:08:33
*/
public class UtilDBbyMyBatis {
public static SqlSession sqlsssion; /**
* 获取SqlSession
*
* @return
* @throws IOException
*/
public static SqlSession GetSqlSession() throws IOException {
if (null != sqlsssion) {
return sqlsssion;
} else {
//Resources.getResourcesAsStream("xxx");这个是以src为根目录的
InputStream ips = Resources.getResourceAsStream("com/test/mybatis/config/Configuration.xml");
// 获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(ips);
sqlsssion = factory.openSession();
return sqlsssion;
} }
}
Configuration.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 configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration>
<settings>
<setting name="useGeneratedKeys" value="false" />
<setting name="useColumnLabel" value="true" />
</settings> <!-- <typeAliases> <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
</typeAliases> --> <environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value="" />
</transactionManager>
<dataSource type="UNPOOLED">
<!-- Oracle数据库配置 -->
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl2" />
<property name="username" value="hr" />
<property name="password" value="hr" />
</dataSource>
</environment>
</environments> <!-- 配置的实体类 20161106添加 -->
<mappers>
<!-- <mapper resource="org/apache/ibatis/submitted/complex_property/User.xml" /> -->
<!-- 这个路径是从src下开始的,即以src作为根目录的,
这点和Resources.getResourcesAsStream("xx")里的xx一样,都是指向的具体文件的路径
,都是以src为根目录 -->
<mapper resource="com/test/mybatis/config/MyUser.xml" />
</mappers> </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:

 package com.test.mybatis.entity;

 public class MyUser {
private Long id; /*
* user specified user ID
*/
private String username; /*
* encrypted password
*/
private EncryptedString password; String administrator; public MyUser() {
setUsername(new String());
setPassword(new EncryptedString());
setAdministrator("我是admin");
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public EncryptedString getPassword() {
return password;
} public void setPassword(EncryptedString password) {
this.password = password;
} public String getAdministrator() {
return administrator;
} public void setAdministrator(String administrator) {
this.administrator = administrator;
} }
MyBatisDemo01.java
 package com.test.mybatis.mybatistest;

 import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger; import com.test.mybatis.entity.EncryptedString;
import com.test.mybatis.entity.MyUser;
import com.test.mybatis.service.MaintainService;
import com.test.mybatis.util.UtilDBbyMyBatis; /**
* MyBatis测试类
*
* @author Wei
* @time 2016年11月6日 下午5:13:18
*/
public class MyBatisDemo01 {
public static void main(String[] args) throws IOException { SqlSession sqlSession = UtilDBbyMyBatis.GetSqlSession();
/*
* SqlSession.selectList(String str);里的str是根据实体类映射文件里的id来寻找的,
* 实际上框架内部是通过"命名空间.str"的形式来查找对应的sql语句的(这个命名空间就是
* 映射文件的namespace的值,具体到这个例子中就是<mapper namespace="MyUser22">),比如
* sqlSession.selectList("queryMyUserList_wyl");这行代码,框架内部是根据
* sqlSession.selectList("MyUser22.queryMyUserList_wyl");来寻找的,
*/
List<MyUser> list = sqlSession.selectList("queryMyUserList_wyl"); int len = list.size();
for (int i = 0; i < len; i++) {
System.out.println(list.get(i).getUsername() + ",id=" + list.get(i).getId());
}
System.out.println("==============分割线==============");
MyUser user = new MyUser();
user.setUsername("weiyongle359");
user.setAdministrator("hr");
// user.setId(new Long(359));
user.setPassword(new EncryptedString());
System.out.println("==111111111111111111============分割线==============");
Logger log = Logger.getRootLogger();
// log.debug("");
// log.info("");
// log.warn("xxxx");
// log.error("");
List<MyUser> list2 = sqlSession.selectList("queryMyUserListbyName_wyl",user);
System.out.println("==22222222222222222============分割线==============");
int len2 = list2.size();
for (int i = 0; i < len2; i++) {
System.out.println(list2.get(i).getUsername() + ",id=" + list2.get(i).getId());
} System.out.println("测试删除");
int num = new MaintainService().delete("358");
System.out.println("删除了"+num+"条数据"); System.out.println("测试批量删除");
List<String> idlist = new ArrayList<String>();
idlist.add("342");
idlist.add("356");
idlist.add("357");
int num2 = new MaintainService().deleteBatch(idlist);
}
}

Oracle的建表语句:

 --select * from MyUser for update;

 --建表语句
create table MyUser (
id number,
username varchar2(32) not null,
password varchar2(128) not null,
administrator varchar2(5),
primary key (id)
); --插入数据
insert into MyUser
(ID, USERNAME, PASSWORD, ADMINISTRATOR)
values
(BXGX_SEQ_AAZ611.Nextval,
'weiyongle' || BXGX_SEQ_AAZ611.Nextval,
'hr',
'hr');

MyBatis的demo的更多相关文章

  1. MyBatis使用DEMO及cache的使用心得

    下面是一个简单的MyBatis使用DEMO. 整体结构 整体代码大致如下: POM依赖 需要引用两个jar包,一个是mybatis,另一个是mysql-connector-java,如果是maven工 ...

  2. Mybatis入门DEMO

    下面将通过以下步骤说明如何使用MyBatis开发一个简单的DEMO: 步骤一:新建表STUDENTS 字段有: Stu_Id.Stu_Name.Stu_Age.Stu_Birthday CREATE ...

  3. mybatis写demo时遇到的问题

    写demo的时候,用mybatis的配置文件链接数据库,始终链接不上,太急人了.仔细查阅,发现在mysql中新增的表没有事务支持.还有就是mysql搜索引擎支持的不对.我换了一下 innodb的引擎, ...

  4. 最基础的mybatis入门demo

    demo结构 数据库情况 (不会转sql语句 骚瑞) 数据库连接信息 jdbc.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:m ...

  5. MyBatis 入门Demo

    新建数据库my_db,新建表student_tb id为主键,不自动递增. 不必插入数据. 下载MyBatis https://github.com/mybatis/mybatis-3/release ...

  6. Mybatis入门Demo(单表的增删改查)

    1.Mybatis 什么是Mybatis: mybatis是一个持久层框架,用java编写的 它封装了jdbc操作的很多细节,使开发者只需要关注sql语句本身,而无需关注注册驱动.创建连接等繁杂过程 ...

  7. 3.springMVC+spring+Mybatis整合Demo(单表的增删该查,这里主要是贴代码,不多解释了)

    前面给大家讲了整合的思路和整合的过程,在这里就不在提了,直接把springMVC+spring+Mybatis整合的实例代码(单表的增删改查)贴给大家: 首先是目录结构: 仔细看看这个目录结构:我不详 ...

  8. mybatis框架demo first

    SqlMapConfig.xml: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE con ...

  9. MyBatis入门级Demo

    1.创建Java工程MyBatisTest001,导入jar包(mybatis-3.2.1/mysql-connector-java-5.1.24-bin); 2.创建User表,数据库(MySql) ...

随机推荐

  1. 16.ajax_case01

    # 抓取北京市2018年积分落户公示名单 # 'http://www.bjrbj.gov.cn/integralpublic/settlePerson' import csv import json ...

  2. git 冲突解决的方法

    版权声明:本文为博主原创文章,未经博主同意不得转载. 新博客地址:www.atomicdevelop.com https://blog.csdn.net/believer123/article/det ...

  3. JavaScript对象数组根据某属性sort升降序排序

    1.自定义一个比较器,其参数为待排序的属性. 2.将带参数的比较器传入sort(). var data = [    {name: "Bruce", age: 23, id: 16 ...

  4. UVA1533-Moving Pegs(BFS+状态压缩)

    Problem UVA1533-Moving Pegs Accept:106  Submit:375 Time Limit: 3000 mSec  Problem Description  Input ...

  5. Linux 通过rinetd端口转发来访问内网服务

    可以通过端口映射的方式,来通过具有公网的云服务器 ECS 访问用户名下其它未购买公网带宽的内网 ECS 上的服务.端口映射的方案有很多,比如 Linux 下的 SSH Tunnel.rinetd,Wi ...

  6. 论文笔记(一)---翻译 Rich feature hierarchies for accurate object detection and semantic segmentation

    论文网址: https://arxiv.org/abs/1311.2524 RCNN利用深度学习进行目标检测. 摘要 可以将ImageNet上的进全图像分类而训练好的大型卷积神经网络用到PASCAL的 ...

  7. 项目Alpha冲刺4

    作业描述 课程: 软件工程1916|W(福州大学) 作业要求: 项目Alpha冲刺(团队) 团队名称: 火鸡堂 作业目标: 介绍第四天冲刺的项目进展.问题困难和心得体会 1.团队信息 队名:火鸡堂 队 ...

  8. Java NIO1:浅谈I/O模型

    一.什么是同步?什么是异步? 同步和异步的概念出来已经很久了,网上有关同步和异步的说法也有很多.以下是我个人的理解: 同步就是:如果有多个任务或者事件要发生,这些任务或者事件必须逐个地进行,一个事件或 ...

  9. ASP.NET Core如何使用WSFederation身份认证集成ADFS

    如果要在ASP.NET Core项目中使用WSFederation身份认证,首先需要在项目中引入NuGet包: Microsoft.AspNetCore.Authentication.WsFedera ...

  10. Windows下安装RabbitMQ报错:unable to perform an operation on node时的解决方案

    在计算机领域中,想要程序完成各种功能,那么数据的交流和计算是非常重要的.现在已知的程序动作机制有协程,线程和进程. 在同一个程序中,或者说同一个进程中,数据的交流,传递,计算是非常的简单,只要把相关数 ...