码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis入门详解

时间:2015-05-09 21:55:35      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:

这几天学习Mybatis框架 , 发现有很多地方不是很明白, 查了很多资料, 今天有空做个总结 , 记录一下自己学习中遇到的问题 , 以及解决方法,下面开始:

 

  1. 什么是Mybatis

    MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 201311月迁移到Github

    Mybatis是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架.hibernate都属于orm(对象与关系映射) 框架

     

  2. 背景

    它的前身是iBatis , iBatis也是一个数据映射框架 , 它使我们的Java/.Net应用程序能够更加简洁的跟数据库打交道。iBatis通过一系列的XML配置文件,解耦了对象和存储过程/SQL语句

  3. 环境搭建:

    开发工具: mysql5.6 , eclipse , jdk1.7 , maven3.2.5 , mybatis-3.2.8

    Jar:

     

  4. 入门安装

    使用Maven构建项目,需要将下面的dependency置于pom.xml中:

    <dependency>

    <groupId>org.mybatis</groupId>

    <artifactId>mybatis</artifactId>

    <version>x.x.x</version>

    </dependency>

  5. 开发步骤:
    1. 创建一个maven项目

      技术分享

    2. mysql数据库中创建一个数据库mybatis_0505 , 在创建表tb_user

       

      CREATE TABLE `tb_user` (

      `id` bigint(20) NOT NULL AUTO_INCREMENT,

      `user_name` varchar(100) DEFAULT NULL COMMENT 用户名,

      `password` varchar(100) DEFAULT NULL COMMENT 密码,

      `name` varchar(100) DEFAULT NULL COMMENT 姓名,

      `age` int(10) DEFAULT NULL COMMENT 年龄,

      `sex` tinyint(1) DEFAULT NULL COMMENT 性别,1男性,2女性,

      `birthday` date DEFAULT NULL COMMENT 出生日期,

      `created` datetime DEFAULT NULL COMMENT 创建时间,

      `updated` datetime DEFAULT NULL COMMENT 更新时间,

      PRIMARY KEY (`id`),

      UNIQUE KEY `username` (`user_name`)

      ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

       

      在给表里添加几条数据

INSERT INTO `tb_user` VALUES (‘1‘, ‘zhangsan‘, ‘123456‘, 张三, ‘30‘, ‘1‘, ‘1984-08-08‘, ‘2014-09-19 16:56:04‘, ‘2014-09-21 11:24:59‘);

INSERT INTO `tb_user` VALUES (‘2‘, ‘lisi‘, ‘123456‘, 李四, ‘21‘, ‘2‘, ‘1991-01-01‘, ‘2014-09-19 16:56:04‘, ‘2014-09-19 16:56:04‘);

INSERT INTO `tb_user` VALUES (‘3‘, ‘wangwu‘, ‘123456‘, 王五, ‘22‘, ‘2‘, ‘1989-01-01‘, ‘2014-09-19 16:56:04‘, ‘2014-09-19 16:56:04‘);

INSERT INTO `tb_user` VALUES (‘4‘, ‘zhangwei‘, ‘123456‘, 张伟, ‘20‘, ‘1‘, ‘1988-09-01‘, ‘2014-09-19 16:56:04‘, ‘2014-09-19 16:56:04‘);

INSERT INTO `tb_user` VALUES (‘5‘, ‘lina‘, ‘123456‘, 李娜, ‘28‘, ‘1‘, ‘1985-01-01‘, ‘2014-09-19 16:56:04‘, ‘2014-09-19 16:56:04‘);

INSERT INTO `tb_user` VALUES (‘6‘, ‘lilei‘, ‘123456‘, 李磊, ‘23‘, ‘1‘, ‘1988-08-08‘, ‘2014-09-20 11:41:15‘, ‘2014-09-20 11:41:15‘);

3. 使用maven管理mybatis的包,mybatis所需要的包全都放在pom中添加:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.baidu.mybatis</groupId>

<artifactId>mybatis</artifactId>

<version>1.0.0-SNAPSHOT</version>

 

     <dependencies>

        <dependency>

            <groupId>org.mybatis</groupId>

            <artifactId>mybatis</artifactId>

            <version>3.2.8</version>

        </dependency>

            

            <!-- 日志 -->

            <dependency>

                <groupId>org.slf4j</groupId>

                <artifactId>slf4j-log4j12</artifactId>

                <version>1.6.4</version>

            </dependency>

            

            <!-- 单元测试 -->

            <dependency>

                <groupId>junit</groupId>

                <artifactId>junit</artifactId>

                <version>4.10</version>

                <scope>test</scope>

            </dependency>

            

            <!-- MySql -->

            <dependency>

                <groupId>mysql</groupId>

                <artifactId>mysql-connector-java</artifactId>

                <version>5.1.32</version>

            </dependency>

            

            <!-- 连接池 -->

            <dependency>

                <groupId>com.alibaba</groupId>

                <artifactId>druid</artifactId>

                <version>1.0.9</version>

            </dependency>

            

                <!-- Apache工具组件 -->

            <dependency>

                <groupId>org.apache.commons</groupId>

                <artifactId>commons-lang3</artifactId>

                <version>3.3.2</version>

            </dependency>

            <dependency>

                <groupId>org.apache.commons</groupId>

                <artifactId>commons-io</artifactId>

                <version>1.3.2</version>

            </dependency>

    </dependencies>

 

<build>

        <plugins>

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-compiler-plugin</artifactId>

                <version>3.2</version>

                <configuration>

                    <source>1.7</source>

                    <target>1.7</target>

                    <encoding>UTF-8</encoding>

                </configuration>

            </plugin>

        </plugins>

        <pluginManagement>

            <plugins>

                <!-- 配置Tomcat插件 -->

                <plugin>

                    <groupId>org.apache.tomcat.maven</groupId>

                    <artifactId>tomcat7-maven-plugin</artifactId>

                    <version>2.2</version>

                </plugin>

            </plugins>

        </pluginManagement>

</build>

</project>

会自动下载jar:

技术分享

  1. 2个配置文件 , 一个是jdbc ,一个日志log4j

    在src/main/resources 下创建这2个配置文件

        技术分享

        jdbc.properties配置文件

            jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis_0505?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true

jdbc.username=root

jdbc.password=root

        log4j.properties配置文件:

            log4j.rootLogger=DEBUG,A1

log4j.logger.org.mybatis = DEBUG

log4j.appender.A1=org.apache.log4j.ConsoleAppender

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

  1. 创建实体类 user.java

package com.baidu.mybatis.pojo;

import java.util.Date;

public class User {

private Long id;

// 用户名

private String userName;

// 密码

private String password;

// 姓名

private String name;

// 年龄

private Integer age;

// 性别,1男性,2女性

private Integer sex;

// 出生日期

private Date birthday;

// 创建时间

private Date created;

// 更新时间

private Date updated;

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 String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

public Integer getSex() {

return sex;

}

public void setSex(Integer sex) {

this.sex = sex;

}

public Date getBirthday() {

return birthday;

}

public void setBirthday(Date birthday) {

this.birthday = birthday;

}

public Date getCreated() {

return created;

}

public void setCreated(Date created) {

this.created = created;

}

public Date getUpdated() {

return updated;

}

public void setUpdated(Date updated) {

this.updated = updated;

}

@Override

public String toString() {

return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", name=" + name

+ ", age=" + age + ", sex=" + sex + ", birthday=" + birthday + ", created=" + created

+ ", updated=" + updated + "]";

}

 

}

 4. dao包下,建立一个UserDao接口,在接口中定义一个根据Id找到user的方法 UserDao.java

package com.baidu.mybatis.dao;

import com.baidu.mybatis.pojo.User;

public interface UserDao {

     //查询

     public User queryUserById(Long id);

     //保存

public void saveUser(User user);

//修改

public void updateUser(User user);

//根据id,删除数据

public void deleteUserById(Long id);

}

 

  1. src/main/resources下创 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="com.baidu.mybatis.dao.UserDao">

         <select id="queryID" resultType="cn.itcast.mybatis.pojo.User">

         select *,user_name userName from tb_user where id = #{id};

         </select>

    </mapper>

        Namesepase:空间名称指dao接口包

        这里的<select></select>标签对应UserDao中的queryUserById()方法需要执行的sql语句,

   5.接下来在src/main/resources下创建mybatis-config.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="${jdbc.driver}"/>

    <property name="url" value="${jdbc.url}"/>

    <property name="username" value="${jdbc.username}"/>

    <property name="password" value="${jdbc.password}"/>

    </dataSource>

    </environment>

    </environments>

    <mappers>

        <mapper resource="UserMapper.xml"/>

    </mappers>

    </configuration>

在配置文件中通过定义现在的environment , 来指定目前的开发状态,用jdbc作为事务和连接池的配置与mysql数据库相链接。

 在mappers下写入需要用到的mybatis 需要用到的mapper文件

 

  1. 编写接口的实现类 UserDaoImpl.java

     

  public class UserDaoImpl implements UserDao{

private SqlSessionFactory sqlSessionFactory;

public UserDAOImpl(SqlSessionFactory sqlSessionFactory){

this.sqlSessionFactory = sqlSessionFactory;

}

@Override

public User queryUserById(Long id) {

SqlSession session = this.sqlSessionFactory.openSession();

User user = session.selectOne("userDAO.queryUserById", id);

session.close();

return user;

}

@Override

public void saveUser(User user) {

SqlSession session = this.sqlSessionFactory.openSession();

session.insert("userDAO.saveUser", user);

//提交事物

session.commit();

session.close();

}

@Override

public void updateUser(User user) {

SqlSession session = this.sqlSessionFactory.openSession();

session.update("userDAO.updateUser", user);

//提交事物

session.commit();

session.close();

}

@Override

public void deleteUserById(Long id) {

SqlSession session = this.sqlSessionFactory.openSession();

session.delete("userDAO.deleteUserById", id);

//提交事物

session.commit();

session.close();

}

}

6. 测试类 UserDaoImplTest

public class UserDAOImplTest {

private UserDAO userDAO;

@Before

public void setUp() throws Exception {

String resource = "mybatis-config.xml";

InputStream inputStream = Resources.getResourceAsStream(resource);

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

this.userDAO = new UserDAOImpl(sqlSessionFactory);

}

@Test

public void testQueryUserById() {

User user = this.userDAO.queryUserById(1L);

System.out.println(user);

}

@Test

public void testSaveUser() {

User user = new User();

user.setAge(20);

user.setBirthday(new Date());

user.setName("test_1");

user.setPassword("123456");

user.setSex(1);

user.setUserName("test_username_1");

this.userDAO.saveUser(user);

}

@Test

public void testUpdateUser() {

User user = this.userDAO.queryUserById(2L);

user.setAge(30);

this.userDAO.updateUser(user);

}

@Test

public void testDeleteUserById() {

this.userDAO.deleteUserById(6L);

}

}

Mybatis入门详解

标签:

原文地址:http://www.cnblogs.com/jzcq/p/4491011.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!