一、实现单一查询

1)核心配置文件:Configuration.xml

1 <?xml version="1.0" encoding="UTF-8"?>2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">3 <configuration>4     <environments default="development">5         <environment id="development">6             <transactionManager type="JDBC" />7             <!-- 配置数据库连接信息 -->8             <dataSource type="POOLED">9                 <property name="driver" value="com.mysql.jdbc.Driver" />
10                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
11                 <property name="username" value="root" />
12                 <property name="password" value="XDP" />
13             </dataSource>
14         </environment>
15     </environments>
16
17 </configuration>

2)定义表所对应的实体类

package me.gacl.domain;/*** @author gacl* users表所对应的实体类*/
public class User {//实体类的属性和表的字段名称一一对应private int id;private String name;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", age=" + age + "]";}
}

3)定义操作users表的sql映射文件userMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)-->
<mapper namespace="me.gacl.mapping.userMapper"><!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回User类就是users表所对应的实体类--><!-- 根据id查询得到一个user对象--><select id="getUser" parameterType="int" resultType="me.gacl.domain.User">select * from users where id=#{id}</select>
</mapper>

4)在conf.xml文件中注册userMapper.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC" /><!-- 配置数据库连接信息 --><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis" /><property name="username" value="root" /><property name="password" value="XDP" /></dataSource></environment></environments><mappers><!-- 注册userMapper.xml文件, userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml--><mapper resource="me/gacl/mapping/userMapper.xml"/></mappers></configuration>

5)编写测试代码:执行定义的select语句

package me.gacl.test;import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import me.gacl.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class Test1 {public static void main(String[] args) throws IOException {//mybatis的配置文件String resource = "conf.xml";//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);//构建sqlSession的工厂SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);//使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)//Reader reader = Resources.getResourceAsReader(resource); //构建sqlSession的工厂//SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);//创建能执行映射文件中sql的sqlSessionSqlSession session = sessionFactory.openSession();/*** 映射sql的标识字符串,* me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,* getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL*/String statement = "me.gacl.mapping.userMapper.getUser";//映射sql的标识字符串//执行查询返回一个唯一user对象的sqlUser user = session.selectOne(statement, 1);System.out.println(user);}
}

二、使用MyBatis对表执行CRUD操作——基于XML的实现

使用到的工具类:

package com.ual.Utils;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.Reader;public class MybatisUtil {/*** 获取sessionFactory* @return  SqlSessionFactory*/public static SqlSessionFactory getSqlSessionFactory() throws IOException {String resource="Configuration.xml";Reader resourceAsReader = Resources.getResourceAsReader(resource);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsReader);return factory;}/*** 获取sqlSession* @return SqlSession*/public static SqlSession getSqlSession() throws IOException {return getSqlSessionFactory().openSession();}/*** 获取SqlSession* @param isAutoCommit*         true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务*         false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务* @return SqlSession*/public static SqlSession getSqlSession(boolean isAutoCommit) throws IOException {return getSqlSessionFactory().openSession(isAutoCommit);}}

1.UserMapper.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 athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed 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 andlimitations under the License.-->
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="User"><resultMap type="com.ual.domain.User" id="UserResult"><id column="id" jdbcType="INTEGER" property="id"/><result column="username" jdbcType="VARCHAR" property="username"/><result column="password" jdbcType="VARCHAR" property="password"/></resultMap><!--根据id查询一个User对象--><select id="getById" parameterType="Integer" resultMap="UserResult">select * from user where id=#{id}</select><!--创建用户--><insert id="addUser" parameterType="com.ual.domain.User">insert into user(username,password)values (#{username},#{password})</insert><!--删除用户--><delete id="deleteUser" parameterType="String">delete from user where username=#{username}</delete><!--查询全部用户--><select id="selectAll" resultMap="UserResult">select * from user</select>
</mapper>

2.dao实现类

package com.ual.dao;import com.ual.Utils.MybatisUtil;
import com.ual.domain.User;
import org.apache.ibatis.session.SqlSession;import java.util.List;public class UserDaoImpl implements UserDao {SqlSession sqlSession=null;@Overridepublic void selectById(Integer id) {try{sqlSession = MybatisUtil.getSqlSession();User user = sqlSession.selectOne("User.getById",id);System.out.println(user);}catch (Exception e){e.printStackTrace();}finally {if(sqlSession!=null)sqlSession.close();}}@Overridepublic void insert(User user) {try{sqlSession = MybatisUtil.getSqlSession(true);sqlSession.insert("User.addUser",user);}catch (Exception e){e.printStackTrace();}finally {if(sqlSession!=null)sqlSession.close();}}@Overridepublic void deleteByName(String name) {try{sqlSession = MybatisUtil.getSqlSession(true);sqlSession.insert("User.deleteUser",name);}catch (Exception e){e.printStackTrace();}finally {if(sqlSession!=null)sqlSession.close();}}@Overridepublic void update(User user) {}@Overridepublic List<User> selectAll() {try{sqlSession = MybatisUtil.getSqlSession(true);//查询到的结果,自动封装成List<User>return sqlSession.selectList("User.selectAll");}catch (Exception e){e.printStackTrace();}finally {if(sqlSession!=null)sqlSession.close();}return null;}
}

3.单元测试

package com.ual;import com.ual.dao.MessageDao;
import com.ual.dao.UserDaoImpl;
import com.ual.domain.User;import java.util.List;public class Test {@org.junit.Testpublic void test(){UserDaoImpl userDao = new UserDaoImpl();userDao.selectById(1);}@org.junit.Testpublic void test2(){User user1 = new User();user1.setUsername("xx");user1.setPassword("1234");UserDaoImpl userDao = new UserDaoImpl();userDao.insert(user1);}@org.junit.Testpublic void test3(){UserDaoImpl userDao = new UserDaoImpl();userDao.deleteByName("xx");}@org.junit.Testpublic void test4(){UserDaoImpl userDao = new UserDaoImpl();List<User> users = userDao.selectAll();for (User u:users) {System.out.println(u);}}}

三、使用MyBatis对表执行CRUD操作——基于注解的实现

1.定义sql映射的接口

package com.ual.Mapping;import com.ual.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;import java.util.List;/*** 定义映射的接口*/
public interface UserMapping {//使用@Insert注解指明方法要执行的SQL@Insert("insert into user(username,password )values(#{username},#{password})")public int add(User user);//使用@Deslete注解指明deleteByName方法要执行的sql@Delete("delete from user where username=#{username}")public int deleteByName(String name);@Update("update user set username=#{username},password=#{password} where id= #{id}")public int update(User user);@Select("select * from user where id =#{id}")public User getById(int id );@Select("select * from user")public List<User> getAll();}

2、在conf.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 athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed 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 andlimitations under the License.-->
<!DOCTYPE configurationPUBLIC "-//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="User" type="com.ual.domain.User"/></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"><property name="" value=""/></transactionManager><dataSource type="UNPOOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql:///mybatis?serverTimezone=GMT%2B8"/><property name="username" value="root"/><property name="password" value="1234"/></dataSource></environment></environments><mappers><mapper resource="User.xml"/><!--注册UserMapping映射接口--><mapper class="com.ual.Mapping.UserMapping"/></mappers></configuration>

3.测试

 @org.junit.Testpublic void test5() throws IOException {SqlSession sqlSession = MybatisUtil.getSqlSession(true);//获得会话后,获取接口,通过获取的接口调用里面定义的方法UserMapping mapper = sqlSession.getMapper(UserMapping.class);User user = new User();user.setUsername("wzh");user.setPassword("123o");mapper.add(user);sqlSession.close();}

转载于:https://www.cnblogs.com/UalBlog/p/10741222.html

MyBatis入门2相关推荐

  1. Mybatis入门之动态sql

    Mybatis入门之动态sql 通过mybatis提供的各种标签方法实现动态拼接sql. 1.if.where.sql.include标签(条件.sql片段) <sql id="sel ...

  2. MyBatis1:MyBatis入门

    MyBatis是什么 MyBatis是什么,MyBatis的jar包中有它的官方文档,文档是这么描述MyBatis的: MyBatis is a first class persistence fra ...

  3. MyBatis(1):MyBatis入门

    MyBatis是什么 MyBatis是什么,MyBatis的jar包中有它的官方文档,文档是这么描述MyBatis的: MyBatis is a first class persistence fra ...

  4. MyBatis-学习笔记02【02.Mybatis入门案例】

    Java后端 学习路线 笔记汇总表[黑马程序员] MyBatis-学习笔记01[01.Mybatis课程介绍及环境搭建][day01] MyBatis-学习笔记02[02.Mybatis入门案例] M ...

  5. mybatis入门(七)之日志

    转载自    mybatis入门(七)之日志 Mybatis 的内置日志工厂提供日志功能,内置日志工厂将日志交给以下其中一种工具作代理: SLF4J Apache Commons Logging Lo ...

  6. mybatis入门(一)之基础安装

    转载自  mybatis入门 安装 要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于 classpath 中即可. 如果使用 Maven 来构建项目,则需将下面的 dep ...

  7. Mybatis入门程序增删改查操作

    学习目标 了解Mybatis的基本知识 熟悉Mybatis的工作原理 掌握Mybatis入门程序的编写 文章目录 1.初始Mybatis 2.Mybatis入门程序 3.Mybatis操作总结 1.初 ...

  8. Mybatis入门 使用注解

    使用XML方式地址为Mybatis入门 使用XML 1.目录结构 2.需要修改的地方 1.mybatis的配置文件 <?xml version="1.0" encoding= ...

  9. Mybatis入门 使用XML

    1.项目结构 2.详细代码 数据库: 1.创建实体类bean package com.itheima.domain;import java.io.Serializable; import java.u ...

  10. MyBatis入门(二)---一对一,一对多

    一.创建数据库表 1.1.创建数据表同时插入数据 /* SQLyog Enterprise v12.09 (64 bit) MySQL - 5.6.27-log : Database - mybati ...

最新文章

  1. 天草脱壳视频学习笔记
  2. 【整理】SAP货币汇率转换
  3. 万字总结:开源软件通识基础课第三周知识点总结
  4. 数据结构之并查集:路径压缩继续优化并查集——20
  5. OpenCV基本函数使用--Python
  6. 【李宏毅2020 ML/DL】P59 Unsupervised Learning - Auto-encoder
  7. java获取当前年月日历_转:JavaCalendar获取年、月、日、时间
  8. nvidia显卡cuda的性能_苦等10年!512 CUDA满血GTX 480终于出现:性能提升6%、功耗暴增43%...
  9. c++矩阵的转置和快速转置
  10. 使用 IDEA Maven 整合 SSM 框架(Spring+SpringMVC+Mybatis)
  11. ITMO-HDU Image Processing Lab4 Report
  12. 知乎高赞:哪些事坚持做3个月就会有巨大改变?
  13. 【Python数据分析与处理 实训01】 ---- 菜品订单信息分析(数据了解及简单统计)
  14. C# WebService 远程服务器返回错误:(500)内部服务器错误
  15. 概率论05 - 随机变量及其分布函数
  16. 激光计算机是谁发明的,五个难以解释的古发明,第四个是计算机祖宗,第五个激光武器雏形...
  17. jadx学习记录01
  18. 到底什么是嵌入式?什么是单片机?
  19. 使用EventLog类写Windows事件日志
  20. QQ聊天对话框(Js实现,支持表情插入文本中间)

热门文章

  1. 49.什么是拼接技术?
  2. C++程序设计之可调用对象与标准库function
  3. 人脸识别屡遭非议,会成为“潘多拉魔盒”吗?
  4. C++ MFC界面读写USB HID设备数据程序
  5. linux用卸载软件管理,Linux下软件的安装卸载管理
  6. 计算机硬件的组装实践,毕业论文-计算机硬件组装实践.doc
  7. python爬去学校_python爬取学校教务系统
  8. @PreAuthorize 权限控制的原理
  9. ant java build_Ant--基于java的build工具
  10. php动态网页转换成html,怎么把动态的php文件转换成静态的html文件,html文件是php文件…...