什么是 MyBatis ?

MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

教程链接

https://mybatis.github.io/mybatis-3/zh/index.html

第一个helloworld程序源代码

①导入jar包

mybatis-3.2.8.jar

mysql-connector-java-5.1.18-bin.jar

②配置mybatis的配置文件Configuration.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>
<typeAliases>
<typeAlias alias="User" type="com.oracle.pojo.User"/>
</typeAliases>

<!--environments  可以填两种值

development:开发者模式

work:工作模式

-->

<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://127.0.0.1:3306/mybatis" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>

<!--导入实体类的映射文件-->
<mappers>
<mapper resource="com/oracle/pojo/User.xml"/>
</mappers>
</configuration>

③实体类

package com.oracle.pojo;

public class User {

private int id;
private String userName;
private String userAge;
private String userAddress;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getUserAge() {
return userAge;
}

public void setUserAge(String userAge) {
this.userAge = userAge;
}

public String getUserAddress() {
return userAddress;
}

public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}

@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", userAge="
+ userAge + ", userAddress=" + userAddress + "]";
}

}

④实体类的配置文件User.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="com.oracle.pojo.UserMapper">
<select id="selectUserByID" parameterType="int" resultType="User">
select * from user where id = #{id}
</select>
</mapper>

⑤测试类

package com.oracle.test;

import java.io.Reader;

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 com.oracle.pojo.User;

public class Test {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;

static{
try{
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}catch(Exception e){
e.printStackTrace();
}
}

public static SqlSessionFactory getSession(){
return sqlSessionFactory;
}

public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {

//"com.oracle.pojo.UserMapper.selectUserByID"是根据实体类的配置文件写的,com.oracle.pojo.UserMapper是配置文件的namespace,selectUserByID是select的id
User user = (User) session.selectOne("com.oracle.pojo.UserMapper.selectUserByID", 1);
System.out.println(user);
} finally {
session.close();
}
}
}

基于xml实现crud

1). 定义sql 映射xml 文件:

<insert id="insertUser" parameterType="com.atguigu.ibatis.bean.User">
insert into users(name, age) values(#{name}, #{age});
</insert>
<delete id="deleteUser" parameterType="int">
delete from users where id=#{id}
</delete>
<update id="updateUser" parameterType="com.atguigu.ibatis.bean.User">
update users set name=#{name},age=#{age} where id=#{id}
</update>
<select id="selectUser" parameterType="int" resultType="com.atguigu.ibatis.bean.User">
select * from users where id=#{id}
</select>
<select id="selectAllUsers" resultType="com.atguigu.ibatis.bean.User">
select * from users
</select>

2). 在config.xml 中注册这个映射文件
<mapper resource="net/lamp/java/ibatis/bean/userMapper.xml"/>

3). 在dao 中调用:

/*//增
int count = session.insert("com.oracle.pojo.UserMapper.addUser", new User(-1,"kkk","12","nnnn"));
System.out.println(count);*/

/*改
* int count = session.update("com.oracle.pojo.UserMapper.updateUser", new User(3, "kkk2222", "30", "mmmmmm"));
System.out.println(count);*/

/*删
* session.delete("com.oracle.pojo.UserMapper.deleteUser", 3);*/

/*获取所有
* List<User> users = session.selectList("com.oracle.pojo.UserMapper.getAllUser");
System.out.println(users);*/

/*获取一个
* User user = (User) session.selectOne("com.oracle.pojo.UserMapper.selectUserByID", 1);
System.out.println(user);*/

基于注解实现crud

1). 定义sql 映射的接口

package com.oracle.pojo;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

public interface UserMapperImp {
@Insert("insert into user(userName,userAge,userAddress) values (#{userName},#{userAge},#{userAddress})")
public int add(User user);
@Delete("delete from user where id = #{id}")
public void delete(int id);
@Update("update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}")
public void update(User user);
@Select("select * from user")
public List<User> getAll();
@Select("select * from user where id = #{id}")
public User getOne(int id);
}

2). 在config 中注册这个映射接口

<mapper class="com.atguigu.ibatis.crud.ano.UserMapperImp"/>

3). 在dao 类中调用

//--------基于注解---------
UserMapperImp mapper = session.getMapper(UserMapperImp.class);
//mapper.add(new User(-1, "bb", "22", "cc"));
//mapper.delete(4);
//mapper.update(new User(5, "bbbb", "22", "cc"));
/*List<User> users = mapper.getAll();
System.out.println(users);*/
User user = mapper.getOne(1);
System.out.println(user);

几个可以优化的地方

连接数据库的配置单独放在一个properties 文件中

在配置文件中

<properties resource="db.properties"/>
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />

为实体类定义别名,简化sql 映射xml 文件中的引用

<typeAliases>
<typeAlias type="com.atguigu.ibatis.bean.User" alias="User"/>
</typeAliases>

可以在src 下加入log4j 的配置文件,打印日志信息

1. 添加jar:
log4j-1.2.16.jar

2.配置log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="debug" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>

mybatis学习的更多相关文章

  1. MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)

    本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ...

  2. MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合(转载)

      孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(八)--Mybatis3.x与Spring4.x整合 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: m ...

  3. MyBatis学习总结(七)——Mybatis缓存(转载)

      孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(七)--Mybatis缓存 一.MyBatis缓存介绍 正如大多数持久层框架一样,MyBatis 同样提供了一级缓存和二级缓存的 ...

  4. (原创)mybatis学习二,spring和mybatis的融合

    mybatis学习一夯实基础 上文介绍了mybatis的相关知识,这一节主要来介绍mybaits和spring的融合 一,环境搭建 1,jar包下载,下载路径为jar包 2,将包导入到java工程中 ...

  5. (原创)mybatis学习一,夯实基础

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

  6. MyBatis学习--简单的增删改查

    jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...

  7. MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作

    上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...

  8. 【Todo】Mybatis学习-偏理论

    之前写过好几篇Mybatis相关的文章: http://www.cnblogs.com/charlesblc/p/5906431.html  <SSM(SpringMVC+Spring+Myba ...

  9. MyBatis学习系列三——结合Spring

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring MyBatis在项目中应用一般都要结合Spring,这一章主要把MyBat ...

  10. MyBatis学习系列二——增删改查

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...

随机推荐

  1. centos中安装字体

    转载自:http://blog.csdn.net/wlwlwlwl015/article/details/51482065 在使用phantomjs做自动化网页截图时,发现截图都没有文字.最后好久才发 ...

  2. poj 1328 Radar Installation

    题目链接:http://poj.org/problem?id=1328 题意:给出海上有n个小岛的坐标,求发出的信号可以覆盖全部小岛的最少的雷达个数.雷达发射信号是以雷达为圆心,d为半径的圆,雷达都在 ...

  3. onthink 数据库连接配置

    define('UC_DB_DSN', 'mysql://root:@127.0.0.1:3306/app'); // 数据库连接,使用Model方式调用API必须配置此项 /* 数据库配置 */ ' ...

  4. 张艾迪(创始人): 整合全新的UIW.AD概念模式

    The World No.1 Girl :Eidyzhang The World No.1 Internet Girl :Eidyzhang AOOOiA.global Founder :Eidyzh ...

  5. 20169212《Linux内核原理与分析》 第九周作业

    可执行程序的装载 一.预处理.编译.链接和目标文件的格式 可执行程序是怎么来的?通过以下这个图来呈现过程: 以我们常写的helloworld为例.我们编写了一个helloworld的.c文件,我们来把 ...

  6. 原生js通过prottype写的一个简单拖拽

    <!DOCTYPE html> <head> <meta charset="utf-8"/> <title></title&g ...

  7. WebAPI返回数据类型解惑

    本文来自:http://www.cnblogs.com/lzrabbit/archive/2013/03/19/2948522.html 最近开始使用WebAPI,上手很容易,然后有些疑惑 1.Web ...

  8. MongoDB 驱动以及分布式集群读取优先级设置

    本文主要介绍使用MongoDB C驱动读取分布式MongoDB集群时遇到的坑,主要在读取优先级和匹配tag上:同时简单介绍Python驱动.Node.js驱动.Mongoose驱动如何使用读取优先级和 ...

  9. EF中的Code First

     一些概念 Ÿ POCO POCO(Plain Old CLR Object)的概念是从java的POJO借用而来,而两者的含义是一致的,不同的仅仅是使用的语言不一样.所以POCO的解释就是“Plai ...

  10. CentOS6.5 下安装 texlive2015 并设置 ctex 中文套装

    0 卸载旧版本的 texlive 0.1 卸载 texlive2007 如果系统没有安装过texlive,则跳过第0步. 可以在终端中使用如下命令查询本机已经安装的tex和latex版本: [She@ ...