把以前写的关于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. SQL FULL JOIN 关键字

    SQL FULL JOIN 关键字 只要其中某个表存在匹配,FULL JOIN 关键字就会返回行. FULL JOIN 关键字语法 SELECT column_name(s) FROM table_n ...

  2. Doc2vec实现原理

    论文来源:https://www.eecs.yorku.ca/course_archive/2016-17/W/6412/reading/DistributedRepresentationsofSen ...

  3. 爬取伯乐在线文章(五)itemloader

    ItemLoader 在我们执行scrapy爬取字段中,会有大量的CSS或是Xpath代码,当要爬取的网站多了,要维护起来很麻烦,为解决这类问题,我们可以根据scrapy提供的loader机制. 导入 ...

  4. log4net配置文件

    <?xml version="1.0" encoding="utf-8"?> <configuration> <configSec ...

  5. 设计模式(5)原型模式(Prototype)

    设计模式(0)简单工厂模式 设计模式(1)单例模式(Singleton) 设计模式(2)工厂方法模式(Factory Method) 设计模式(3)抽象工厂模式(Abstract Factory) 设 ...

  6. PIL、Pillow安装使用方法

    PIL(Python Imaging Library)是Python常用的图像处理库,而Pillow是PIL的一个友好Fork,提供了了广泛的文件格式支持,强大的图像处理能力,主要包括图像储存.图像显 ...

  7. hackbar增强版 & 在Firefox上安装未通过验证的扩展

    hackbar是Firefox的经典插件之一.介绍如下(懒得翻译了) This toolbar will help you in testing sql injections, XSS holes a ...

  8. display:inline-block 来解决盒子高度不一样,造成的盒子浮动

    <style> ul{ width: 320px; //给父元素添加这两个属性 font-size: 0px; text-align: center/left; } li{ width: ...

  9. Maven学习第4期---Maven简单使用

    一.Maven常用命令 在学习使用Maven构建项目之前,先来了解一下Maven一些实用的命令.mvn的命令有很多,在项目开发中,理解了下面的几个常用命令后,运用maven就基本没有问题了.Maven ...

  10. Java系统高并发之Redis后端缓存优化

    一:前端优化 暴露接口,按钮防重复(点击一次按钮后就变成禁用,禁止重复提交) 采用CDN存储静态化的页面和一些静态资源(css,js等) 二:Redis后端缓存优化 Redis 是完全开源免费的,遵守 ...