mybatis简介

Mybatis是在jdbc的基础之上封装而成的持久层框架。
Mybatis是一个ORM框架。ORM(object relational mapping):对象关系型映射

搭建mybatis环境

 <!-- 设置项目属性 -->
<properties>
<argLine>-Dfile.encoding=UTF-8</argLine>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- 依赖管理 -->
<dependencies>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- mybatis框架 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
</dependencies>

mybatis配置文件(配置连接数据库信息)

 在src/main/resources下创建mybatisConfig.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="mysqlDB">
<!-- 配置一个数据库连接环境 -->
<environment id="mysqlDB">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<!-- url -->
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"></property>
<!-- name -->
<property name="username" value="root"></property>
<!-- password -->
<property name="password" value="root"></property>
<!-- driver class -->
<property name="driver" value="com.mysql.jdbc.Driver"></property>
</dataSource>
</environment>
</environments>
<!-- mybatis映射文件 -->
<mappers>
<mapper resource="mapper/UserEntityMapper.xml"></mapper>
</mappers>
</configuration> 主题结构:
<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)>
<!ELEMENT mapper (cache-ref | cache | resultMap* | parameterMap* | sql* | insert* | update* | delete* | select* )+>

mybatis映射文件

 <?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="com.offcn.mybatis.entity">
<!-- insert -->
<insert id="insertUser">
insert into tbl_user values(2,'scott','tiger',25)
</insert>
</mapper>

常用API

public class TestMybatis {
public static void main(String[] args) throws IOException {
// 加载配置文件
Reader reader = Resources.getResourceAsReader("mybatisConfig.xml");
// 创建构造器对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// 创建工厂
SqlSessionFactory sqlSessionFactory = builder.build(reader);
//创建执行对象
SqlSession session = sqlSessionFactory.openSession();
// 执行sql语句
session.insert("insertUser");
// 提交事务
session.commit();
session.close();
}
}

向SQL语句传参数方式

 (1)传对象

     <update id="updateUser" parameterType="UserEntity">
update tbl_user set
uname=#{uname},upass=#{upass},uage=#{uage} where
uid=#{uid}
</update>
public void updateUser() {
UserEntity user = new UserEntity(8, "紫衫龙王", "qkdny", 41);
// 创建执行对象
SqlSession session = sqlSessionFactory.openSession();
// 执行sql语句
session.insert("updateUser", user);
// 提交事务
session.commit();
session.close();
}
(2)传map对象
public void queryMap() {
// 构造条件
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "scott");
map.put("password", "tiger");
// 创建执行对象
SqlSession session = sqlSessionFactory.openSession();
// 执行sql语句
List<UserEntity> list = session.selectList("queryMap", map);
for (UserEntity user : list) {
System.out.println(user);
}
session.close();
}
<!-- 根据用户名和密码查询 -->
<select id="queryMap" resultType="UserEntity" parameterType="java.util.Map">
SELECT uid,uname,upass,uage from tbl_user where uname=#{name} and upass=#{password}
</select>
(3)直接传变量
public void queryById() {
// 创建执行对象
SqlSession session = sqlSessionFactory.openSession();
// 执行sql语句
UserEntity user = (UserEntity) session.selectOne("queryById", 5);
System.out.println(user);
session.close();
}
<select id="queryById" parameterType="int" resultType="UserEntity">
SELECT uid,uname,upass,uage from tbl_user where uid=#{uid}
</select>

使用实体类别名

 <typeAliases>
<!-- 设置实体类别名 --> 要根据属性顺序设置该属性,不然配置文件报错
<typeAlias type="com.offcn.mybatis.entity.UserEntity" alias="UserEntity"></typeAlias>
</typeAliases> <insert id="insertUserWithParam" parameterType="UserEntity">//此处就可以使用别名了
insert into tbl_user(uid,uname,upass,uage) values(#{uid},#{uname},#{upass},#{uage})
</insert>

获取sql结果的方式

获取对象
<!-- query id resultType:设定返回值-->
<select id="queryById" parameterType="int" resultType="UserEntity">
SELECT uid,uname,upass,uage from tbl_user where uid=#{uid}
</select> @Test
public void queryById() {
// 创建执行对象
SqlSession session = sqlSessionFactory.openSession();
// 执行sql语句,获取对象
UserEntity user =(UserEntity)session.selectOne("queryById", 5);
System.out.println(user);
session.close();
} 获取集合
<!-- query All -->
<select id="queryAll" resultType="UserEntity">
SELECT uid,uname,upass,uage from tbl_user
</select>
@Test
public void queryAll() {
// 创建执行对象
SqlSession session = sqlSessionFactory.openSession();
// 执行sql语句,获取list集合
List<UserEntity> list=session.selectList("queryAll");
for(UserEntity user:list) {
System.out.println(user);
}
session.close();
}

简单日志使用

 导入log4j依赖

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency> resources下创建日志文件log4j.properties

### set log levels ###
log4j.rootLogger = debug,stdout,log
#, log, index, D, I, W, E ### print log to console ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d %p [%c] - <%m>%n ### create log to file ###
log4j.appender.log = org.apache.log4j.DailyRollingFileAppender
log4j.appender.log.File = /logs/log.log
log4j.appender.log.Append = true
log4j.appender.log.layout = org.apache.log4j.PatternLayout
log4j.appender.log.layout.ConversionPattern= %d %p [%c] - <%m>%n # Control logging for other open source packages
log4j.logger.net.sf.navigator=ERROR
log4j.logger.net.sf.acegisecurity=WARN
log4j.logger.net.sf.acegisecurity.intercept.event.LoggerListener=WARN
log4j.logger.org.apache.commons=ERROR
log4j.logger.org.apache.struts=WARN
log4j.logger.org.displaytag=ERROR
log4j.logger.org.springframework=WARN
log4j.logger.org.apache.velocity=WARN # SqlMap logging configuration...
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.db=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.sqlmap.engine.cache.CacheModel=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientImpl=debug
log4j.logger.com.ibatis.sqlmap.engine.builder.xml.SqlMapParser=debug
log4j.logger.com.ibatis.common.util.StopWatch=debug log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=error
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=error 日志级别
A:off 最高等级,用于关闭所有日志记录。
B:fatal 指出每个严重的错误事件将会导致应用程序的退出。
C:error 指出虽然发生错误事件,但仍然不影响系统的继续运行。
D:warn 表明会出现潜在的错误情形。
E:info 一般和在粗粒度级别上,强调应用程序的运行全程。
F:debug 一般用于细粒度级别上,对调试应用程序非常有帮助。
G:all 最低等级,用于打开所有日志记录。

Mybatis应用入门的更多相关文章

  1. MyBatis学习总结(一)——MyBatis快速入门

    一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以 ...

  2. MyBatis快速入门

    一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以 ...

  3. MyBatis学习总结(一)——MyBatis快速入门(转载)

    本文转载自http://www.cnblogs.com/jpf-java/p/6013537.html MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了 ...

  4. MyBatis入门学习教程-MyBatis快速入门

    一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以 ...

  5. MyBatis学习总结(一)——MyBatis快速入门

    一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以 ...

  6. 【转】MyBatis学习总结(一)——MyBatis快速入门

    [转]MyBatis学习总结(一)——MyBatis快速入门 一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC ...

  7. mybatis快速入门(六)

    前面mybatis的入门程序基本上都写完了,就看大家的灵活运用了,今天来吧前面的整合一下封装一个公共的BaseDao 只需要把前面的改造下然后创建一个BaseDao的接口,其它的继承BaseDao接口 ...

  8. MyBatis学习总结-MyBatis快速入门的系列教程

    MyBatis学习总结-MyBatis快速入门的系列教程 [MyBatis]MyBatis 使用教程 [MyBatis]MyBatis XML配置 [MyBatis]MyBatis XML映射文件 [ ...

  9. MyBatis基础入门《二十》动态SQL(foreach)

    MyBatis基础入门<二十>动态SQL(foreach) 1. 迭代一个集合,通常用于in条件 2. 属性 > item > index > collection : ...

  10. MyBatis基础入门《十九》动态SQL(set,trim)

    MyBatis基础入门<十九>动态SQL(set,trim) 描述: 1. 问题 : 更新用户表数据时,若某个参数为null时,会导致更新错误 2. 分析: 正确结果: 若某个参数为nul ...

随机推荐

  1. Java Redis缓存穿透/缓存雪崩/缓存击穿,Redis分布式锁实现秒杀,限购等

    package com.example.redisdistlock.controller; import com.example.redisdistlock.util.RedisUtil; impor ...

  2. 1、vueJs基础知识01

    vue是框架,vue.js是vue框架的核心js库 库:是一个封装好的特定的方法的集合,提供给开发者使用,库没有控制权,控制权在使用者手中.代表:jQuery.underscore.util 框架:框 ...

  3. 【opencv C++ linux】linux下编译含opencv的C++代码

    首先写一个简单的测试代码 #include <opencv2/opencv.hpp> #include <iostream> #include <string> u ...

  4. python mongo存在插入不存在更新,同时指定如果不存在才插入的字段

    python爬虫的任务数据操作的小技巧 好久没写公众号了,最近太忙了,这里就不多说了.直接根据需求上代码,我想这个应该是大家比较喜欢的, 需求 爬取某网站的项目列表页,获取其url,标题等信息,作为后 ...

  5. 2018-2019-2 网络对抗技术 20165322 Exp8 Web基础

    2018-2019-2 网络对抗技术 20165322 Exp8 Web基础 目录 实验原理 实验内容与步骤 Web前端HTML Web前端javascipt Web后端:MySQL基础:正常安装.启 ...

  6. arcgis python 获得arcgis的版本和安装路径

    import arcpy # Use the dictionary iteritems to iterate through # the key/value pairs from GetInstall ...

  7. make 实例 一 3463

    ######################################################################### # # Makefile used for buil ...

  8. 文章后面的QA或FAQ

    QA:question&answer FAQ: Frequently Asked Questions的缩写,中文意思就是“经常问到的问题”

  9. bat实现每天定时执行命令[windows底下每天重启一下Nginx]

    --试验通过--Windows环境脚本名称:restart.bat脚本内容: @echo offtaskkill /f /fi "IMAGENAME eq nginx.exe"cd ...

  10. Spring cloud微服务安全实战-4-2微服务安全的新挑战

    微服务的环境下,我的业务逻辑不再是在一个单一的进程里,而是分散了很多的进程里.订单.物流.库存.价格.每一个tomcat都是一个进程. 每一个进程,每一个tomcat都有自己的入口点.那么就导致我防范 ...