MyBatis的demo
把以前写的关于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 !"".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的更多相关文章
- MyBatis使用DEMO及cache的使用心得
下面是一个简单的MyBatis使用DEMO. 整体结构 整体代码大致如下: POM依赖 需要引用两个jar包,一个是mybatis,另一个是mysql-connector-java,如果是maven工 ...
- Mybatis入门DEMO
下面将通过以下步骤说明如何使用MyBatis开发一个简单的DEMO: 步骤一:新建表STUDENTS 字段有: Stu_Id.Stu_Name.Stu_Age.Stu_Birthday CREATE ...
- mybatis写demo时遇到的问题
写demo的时候,用mybatis的配置文件链接数据库,始终链接不上,太急人了.仔细查阅,发现在mysql中新增的表没有事务支持.还有就是mysql搜索引擎支持的不对.我换了一下 innodb的引擎, ...
- 最基础的mybatis入门demo
demo结构 数据库情况 (不会转sql语句 骚瑞) 数据库连接信息 jdbc.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:m ...
- MyBatis 入门Demo
新建数据库my_db,新建表student_tb id为主键,不自动递增. 不必插入数据. 下载MyBatis https://github.com/mybatis/mybatis-3/release ...
- Mybatis入门Demo(单表的增删改查)
1.Mybatis 什么是Mybatis: mybatis是一个持久层框架,用java编写的 它封装了jdbc操作的很多细节,使开发者只需要关注sql语句本身,而无需关注注册驱动.创建连接等繁杂过程 ...
- 3.springMVC+spring+Mybatis整合Demo(单表的增删该查,这里主要是贴代码,不多解释了)
前面给大家讲了整合的思路和整合的过程,在这里就不在提了,直接把springMVC+spring+Mybatis整合的实例代码(单表的增删改查)贴给大家: 首先是目录结构: 仔细看看这个目录结构:我不详 ...
- mybatis框架demo first
SqlMapConfig.xml: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE con ...
- MyBatis入门级Demo
1.创建Java工程MyBatisTest001,导入jar包(mybatis-3.2.1/mysql-connector-java-5.1.24-bin); 2.创建User表,数据库(MySql) ...
随机推荐
- 使用c#封装海康SDK出现无法加载 DLL“..\bin\HCNetSDK.dll”: 找不到指定的模块
最近在研究网络摄像头的二次开发,测试了一款海康威视的网络摄像头,程序调试的时候,出现如题的报错. 调试随机自带的demo时,程序运行正常,但当把该程序引入到我自己的程序中时,就开始报错.根据开发软件包 ...
- (0)HomeAssistant 教程
国外:https://www.home-assistant.io/components/light.mqtt/ 中国:https://www.hachina.io/docs/890.html
- jQuery和js之Cookie实现
Web开发者的朋友们基本上都知道,jQuery是对js的封装.今天之所以想讲解这个问题,主要是因为Cookie用的还是比较多,应用场景除了老生常谈的购物车,还有就是用户状态(以我之前开发的一个项目除了 ...
- P1365 WJMZBMR打osu! / Easy-洛谷luogu
传送门 题目背景 原 维护队列 参见P1903 题目描述 某一天WJMZBMR在打osu~~~但是他太弱逼了,有些地方完全靠运气:( 我们来简化一下这个游戏的规则 有nn次点击要做,成功了就是o,失败 ...
- Java多线程(一)多线程基础
一.进程 进程是操作系统结构的基础:是一次程序的执行:是一个程序及其数据在处理机上顺序执行时所发生的活动.操作系统中,几乎所有运行中的任务对应一条进程(Process).一个程序进入内存运行,即变成一 ...
- PHP基础介绍
php之基本操作 1.常用数据类型: 字符串.整形.浮点数.逻辑.数组.对象.NULL. 字符串: $x = "hello"; 整形:$x = 123; 浮点数:$x =1.123 ...
- 记一次 OutOfMemoryError: Java heap space 的排错
1.情况概述 公司以前的某报名系统,项目启动后,在经过用户一段时间的使用之后,项目响应便开始变得极其缓慢,最后几乎毫无反应.日志里输出了一些似乎无关痛痒的异常,逐步修复,项目仍然出现这种情况,且 &q ...
- RabbitMQ详解(一)------简介与安装
RabbitMQ 这个消息中间件,其实公司最近的项目中有用到,但是一直没有系统的整理,最近看完了<RabbitMQ实战 高效部署分布式消息队列>这本书,所以顺便写写. 那么关于 Rabb ...
- jsp相关基础知识
一.JSP简介 JSP全称是Java Server Page,它和Servlet一样,也是sun公司推出的一套开发动态web资源的技术,称为JSP/Servlet规范.其本质也是一个Servlet. ...
- 在IDEA中构建Tomcat项目流程
在IDEA中构建Web项目流程 打开你的IDEA,跟着我走! 第一步:新建项目 第二步:找到Artifacts 点击绿色的+号,如图所示,点一下 这一步很关键,目的是设置输出格式为war包,如果你的项 ...