把以前写的关于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. }
  1. 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:

  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 mapper
  10. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  11. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  12.  
  13. <mapper namespace="MyUser22">
  14. <!-- 配置返回结果所属类 -->
  15. <resultMap type="com.test.mybatis.entity.MyUser" id="UserResult">
  16. <!-- 在数据库里如果是主键,那么就用<id>标签,其他字段用<column>标签 ,
  17. 这里的type对应着java代码中的例如: java.sql.Types.BOOLEAN -->
  18. <id column="id" jdbcType="INTEGER" property="id" />
  19. <!-- column的值对应的是数据库里的字段名,property对应着实体类的属性 -->
  20. <result column="username" jdbcType="VARCHAR" property="username" />
  21. <!-- <result column="password" jdbcType="VARCHAR" property="password.encrypted" /> -->
  22. <result column="administrator" jdbcType="VARCHAR" property="administrator" />
  23. </resultMap>
  24. <!--Java代码使用示例: SqlSession.selectList("queryMyUserList_wyl"); -->
  25. <select id="queryMyUserList_wyl" resultMap="UserResult">
  26. SELECT * FROM MyUser
  27. WHERE 1=1
  28. </select>
  29.  
  30. <select id="queryMyUserListbyName_wyl" parameterType="com.test.mybatis.entity.MyUser" resultMap="UserResult">
  31. SELECT ID,USERNAME,PASSWORD,ADMINISTRATOR FROM MyUser
  32. WHERE 1=1
  33. <!-- <if test="username !=null and !&quot;&quot;.equals(username.trim())"> -->
  34. <if test="username !=null ">
  35. and USERNAME like '%'||#{username}||'%'
  36. </if>
  37. </select>
  38.  
  39. <!--同一个Mapper文件下, 不能有重复的id -->
  40. <!-- <select id="queryMyUserList_wyl" resultMap="UserResult"> SELECT * FROM
  41. MyUser WHERE 1=1 </select> -->
  42.  
  43. <select id="find" parameterType="long" resultMap="UserResult">
  44. SELECT * FROM
  45. MyUser WHERE id = #{id:INTEGER}
  46. </select>
  47. <delete id="deleteOne" parameterType="int">
  48. <!-- where 条件携程 #{_parameter}的形式具体 详见:http://www.imooc.com/video/4350, -->
  49. delete from MyUser where ID = #{_parameter}
  50. </delete>
  51.  
  52. <!-- 批量删除 -->
  53. <delete id="deleteBatch" parameterType="java.util.List">
  54. delete from MyUser where id in (
  55. <!-- 用逗号隔开item属性值代表list集合中的每一项 -->
  56. <foreach collection="list" item="theitem" >
  57. ${theitem}
  58. </foreach>
  59. )
  60. </delete>
  61. </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. }
  1. 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');

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. Linux之命令进阶

    Linux系统的启动过程 1.开机自检 BIOS2.MBR引导3.GRUB菜单4.加载内核5.运行init进程6.从/etc/inittab读取运行级别7.根据/etc/rc.sysinit 初始化系 ...

  2. bootstrap-table 分页

    bootstrap-table   <!DOCTYPE html> <head> <meta charset="UTF-8"/> <tit ...

  3. 6-MVC结构简介

    一.javeEE的项目结构层次:MVC1.Model:模型层(DAO+业务层) 2.View:视图层 jsp3.Control:控制层 servlet 二.分层的原则:1.层与层之间松耦合,层内保持高 ...

  4. Error: Cannot find module 'babel-runtime/regenerator'

    在做调用阿里云短信接口时遇到的一个问题 错误原因:没有正确安装相应的mmodule 解决办法: 第一步:在package.json中加入依赖label-runtime 第二步:在Terminal中 n ...

  5. element-ui中 table表格hover 修改背景色

    增加样式级别就行啦   .el-table--enable-row-hover .el-table__body tr:hover>td{ background-color: #212e3e !i ...

  6. Ubuntu脚本修改IP信息

    #!/bin/bash cd /etc/network #清除4-9行 sed -i '4,9d' interfaces #在第3行添加网卡名称 sed -i "3a auto ${1}&q ...

  7. ubuntu下无法在目录下创建文件夹,权限不足解决办法

    问题详情:偶然在根目录创建文件夹的时候,突然显示错误,当时很惊讶,以前没遇见过这样的问题.当时界面是这样的. 用了一个 cd / 命令从用户磁盘跳到了根目录 使用 mkdir 命令准备创建一个文件夹, ...

  8. win 2008 R2 或以上版本,只有C盘情况下,PHP上传文件,显示不了解决办法

    主要问题:因为没权限 解决办法:给C:\Windows\Temp 加上IIS账户读写权限

  9. 52abp框架asp.net core & Angular快速开发实战视频教程

    课程标题 52abp框架asp.net core & Angular全栈开发实战视频课程 课程简介 从零开始学 52ABP企业开发框架,企业项目是如何开发和技术选型,代码如何管理,团队协同开发 ...

  10. 从 0 到 1 实现 react - 9.onChange 事件以及受控组件

    该系列文章在实现 cpreact 的同时理顺 React 框架的核心内容 项目地址 从一个疑问点开始 接上一章 HOC 探索 抛出的问题 ---- react 中的 onChange 事件和原生 DO ...