Mybatis 原始dao CRUD方法

用到的相關jar包及所用版本以下:java

其中的Mybatis能夠到github.com的網站下載mysql

<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.swift</groupId>
  <artifactId>mybatis02</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
      <dependencies>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.7</version>
        </dependency>
        <!-- mysql驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
</project>

使用mysql數據庫進行測試git

爲了方便修改數據庫參數,使用了db.propertiesgithub

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

在Mybatis的配置文件中加載這個propertiessql

SqlMapConfig.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>
    <!-- 外部引入的配置信息優先級高於子標籤訂義的配置信息 -->
    <properties resource="db.properties">
        <!-- <property name="jdbc.username" value="root" /> -->
    </properties>

    <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>

    <!-- 加載sql映射文件 -->
    <mappers>
        <mapper resource="sqlmap/UserMapper.xml" />
    </mappers>
</configuration>

 

此時項目的結構以下apache

 

與Hibernate的純orm映射(把實體映射成數據庫表,而且表與表的關係也映射了,基本上徹底封裝了sql)不一樣,swift

Mybatis的映射文件是要本身寫SQL的,而不是由Hibernate自動生成session

純潔的pojo實體類mybatis

package com.swift.pojo;

import java.io.Serializable;
import java.util.Date;

public class User
  implements Serializable
{
  private static final long serialVersionUID = 1L;
  private String uid;
  private String username;
  private String password;
  private String name;
  private String email;
  private String telephone;
  private Date birthday;
  private String gender;
  private int state;
  private String code;
  
  public Date getBirthday() {
    return birthday;
}

public void setBirthday(Date birthday) {
    this.birthday = birthday;
}

public String getUid()
  {
    return this.uid;
  }
  
  public void setUid(String uid)
  {
    this.uid = uid;
  }
  
  public String getUsername()
  {
    return this.username;
  }
  
  public void setUsername(String username)
  {
    this.username = username;
  }
  
  public String getPassword()
  {
    return this.password;
  }
  
  public void setPassword(String password)
  {
    this.password = password;
  }
  
  public String getName()
  {
    return this.name;
  }
  
  public void setName(String name)
  {
    this.name = name;
  }
  
  public String getEmail()
  {
    return this.email;
  }
  
  public void setEmail(String email)
  {
    this.email = email;
  }
  
  public String getTelephone()
  {
    return this.telephone;
  }
  
  public void setTelephone(String telephone)
  {
    this.telephone = telephone;
  }
  
  public int getState()
  {
    return this.state;
  }
  
  public void setState(int state)
  {
    this.state = state;
  }
  
  public String getCode()
  {
    return this.code;
  }
  
  public void setCode(String code)
  {
    this.code = code;
  }
  
  public String getGender()
  {
    return this.gender;
  }
  
  public void setGender(String gender)
  {
    this.gender = gender;
  }

@Override
public String toString() {
    return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", name=" + name + ", email="
            + email + ", telephone=" + telephone + ", birthday=" + birthday + ", gender=" + gender + ", state=" + state
            + ", code=" + code + "]";
}
  
}

Mybatis 的sql映射文件 只是寫了SQL語言的CRUD 

經過這個映射UserMapper.xml文件 能夠對User這個pojo類進行相關操做

<?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="test">

    <!-- resultType:返回多條記錄時配置和單條同樣,mybatis會自動把多條數據放到集合裏面 -->
    <select id="queryUserByUsername" parameterType="String"
        resultType="com.swift.pojo.User">
        select * from user where username = #{username}
    </select>
    <select id="queryUserByTelephone" parameterType="String"
        resultType="com.swift.pojo.User">
        select * from user where telephone like #{telephone}
    </select>
    <select id="queryUserByTelephone2" parameterType="String"
        resultType="com.swift.pojo.User">
        select * from user where telephone like '%${value}%'
    </select>

    <insert id="saveUser" parameterType="com.swift.pojo.User">
        INSERT INTO
        USER(uid,username,password,name)
        VALUES(#{uid},#{username},#{password},#{name})
    </insert>

    <update id="updateUserById" parameterType="com.swift.pojo.User">
        UPDATE USER SET    birthday = #{birthday} WHERE uid = #{uid}
    </update>

</mapper>

那麼如何調用這個映射文件中的crud sql配置呢?Mybatis原始的dao的方法須要咱們創建pojo的dao接口實現類,來調用映射文件中sql配置

Dao接口 UserDao.java

package com.swift.dao;

import java.util.List;

import com.swift.pojo.User;

public interface UserDao {
    User queryUserByUsername(String username);
    
    List<User> queryUserByTelephone(String telephone);
    
    List<User>  queryUserByTelephone2(String telephone);
    
    void saveUser(User user);
    
    void updateUserById(User user);
    
}

實體類

package com.swift.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.swift.pojo.User;

public class UserDaoImpl implements UserDao {

    private SqlSessionFactory sqlSessionFactory;
    
    public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    public User queryUserByUsername(String username) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = sqlSession.selectOne("test.queryUserByUsername", username);
        sqlSession.close();
        return user;
    }

    public List<User> queryUserByTelephone(String telephone) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> users = sqlSession.selectList("test.queryUserByTelephone", telephone);
        sqlSession.close();
        return users;
    }

    public List<User> queryUserByTelephone2(String telephone) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> users  = sqlSession.selectList("test.queryUserByTelephone2", telephone);
        sqlSession.close();
        return users;
    }

    public void saveUser(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.insert("test.saveUser", user);
        sqlSession.close();
    }

    public void updateUserById(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.update("test.updateUserById", user);
        sqlSession.close();
    }

}

測試類

package com.swift.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.swift.dao.UserDao;
import com.swift.dao.UserDaoImpl;
import com.swift.pojo.User;

public class UserDaoTest {
    private SqlSessionFactory sqlSessionFactory;

    @Test
    public void testQueryUserById() throws IOException {
        // 建立SqlSessionFactoryBuilder
                SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
                // 加載SqlMapConfig.xml配置文件
                InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
                // 建立SqlsessionFactory
                this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        // 建立DAO
        UserDao userDao = new UserDaoImpl(this.sqlSessionFactory);
        // 執行查詢
        User user = userDao.queryUserByUsername("swift");
        System.out.println(user);
    }
    @Test
    public void testQueryUserByTelephone() throws IOException {
        // 建立SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 加載SqlMapConfig.xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 建立SqlsessionFactory
        this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        // 建立DAO
        UserDao userDao = new UserDaoImpl(this.sqlSessionFactory);
        // 執行查詢
        List<User> users = userDao.queryUserByTelephone("%186%");
        for (User user : users) {
            System.out.println(user);
        }
    }
}

爲了能看到結果

還要有個log日誌文件log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
相關文章
相關標籤/搜索