MyBatis入門案例、增刪改查

1.MyBatis是什麼?(下載地址:https://github.com/mybatis/mybatis-3/releases) java

   MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,而且更名爲MyBatis,實質上Mybatis對ibatis進行一些改進。 mysql

  MyBatis是一個優秀的持久層框架,它對jdbc的操做數據庫的過程進行封裝,使開發者只須要關注 SQL 自己,而不須要花費精力去處理例如註冊驅動、建立connection、建立statement、手動設置參數、結果集檢索等jdbc繁雜的過程代碼。git

  Mybatis經過xml或註解的方式將要執行的各類statement(statement、preparedStatemnt、CallableStatement)配置起來,並經過java對象和statement中的sql進行映射生成最終執行的sql語句,最後由mybatis框架執行sql並將結果映射成java對象並返回。github

MyBatis入門案例:

1.pox.xmljar包sql

 

<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>cn.jpp</groupId>
  <artifactId>SpringMVC_MyBatis_01base</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringMVC_MyBatis_01base</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>


    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.18</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.2</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.1.0</version>
    </dependency>

  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

2.mybatis-config.xml(mybatis的配置文件)數據庫

<?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>
        <!--1.1鎖定要肯定的類型-->
        <!--<typeAlias type="cn.entity.Student" alias="Student"></typeAlias>-->
        <package name="cn.happyb.entity"></package>
    </typeAliases>
    <environments default="mysql">
        <environment id="mysql">
            <!-- 使用jdbc的事務 -->
            <transactionManager type="JDBC" />
            <!-- 使用自帶的鏈接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test" />
                <property name="username" value="jpp" />
                <property name="password" value="jpp" />
            </dataSource>
        </environment>
    </environments>


    <mappers>
        <mapper resource="cn/happyb/dao/StudentDAO.xml" />
    </mappers>
</configuration>

3.實體類(Student)apache

package cn.happyb.entity;

import java.util.Date;

/**
 * Created by 景佩佩 on 2017-01-19.
 */
public class Student {
     private Integer stuno;
     private String stuname;
     private  Integer stuage;
     private Date studate;

    @Override
    public String toString() {
        return "Student{" +
                "stuno=" + stuno +
                ", stuname='" + stuname + '\'' +
                ", stuage=" + stuage +
                ", studate=" + studate +
                '}';
    }

    public Integer getStuno() {
        return stuno;
    }

    public void setStuno(Integer stuno) {
        this.stuno = stuno;
    }

    public String getStuname() {
        return stuname;
    }

    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public Integer getStuage() {
        return stuage;
    }

    public void setStuage(Integer stuage) {
        this.stuage = stuage;
    }

    public Date getStudate() {
        return studate;
    }

    public void setStudate(Date studate) {
        this.studate = studate;
    }
}

StudentDao.javasession

package cn.happyb.dao;

import cn.happyb.entity.Student;

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

/**
 * Created by 景佩佩 on 2017-01-19.
 * 用來操做數據庫的接口
 */
public interface IStudentDAO {
    /**
     * 新增學生
     *
     * @param stu
     * @return
     * @throws IOException
     */

    public int addStu(Student stu);

    /**
     * 刪除學生
     * @param id
     * @return
     * @throws IOException
     */
    public int delStu(int id) throws IOException;

    /**
     * 更新學生信息
     * @param stu
     * @return
     */

    public int editStu(Student stu);

    /**
     * 查詢全部記錄
     * @return
     */
    public List<Student> findAll();

}

StudentDaoImpl.javamybatis

package cn.happyb.dao;

import cn.happyb.entity.Student;
import cn.happyb.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

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

/**
 * Created by 景佩佩 on 2017-01-19.
 */
public class StudentDAOImpl implements IStudentDAO {

    public int addStu(Student stu) {

        //和數據庫通訊的入口,session對象
        SqlSession  session = MyBatisUtil.getSession();
        int flag = session.insert("addstu", stu);

       // session.delete("addstu", stu);

        session.commit();
        return flag;
    }

    public int delStu(int id) throws IOException {
        SqlSession session=MyBatisUtil.getSession();
        int result=session.delete("delStu",id);
        session.commit();
        session.close();
        return result;
    }

    public int editStu(Student stu) {
        SqlSession session=MyBatisUtil.getSession();
        int result=session.update("editStu",stu);
        session.commit();
        session.close();
        return result;
    }

    public List<Student> findAll() {
        SqlSession session=MyBatisUtil.getSession();
        List<Student> list=session.selectList("findAll");
        session.close();;
        return list;
    }
}

StudentDAO.xmloracle

<?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="cn.happyb.dao">
<insert id="addstu">
    insert into student(stuname,stuage,studate) values(#{stuname},#{stuage},#{studate})
    <selectKey resultType="int" keyProperty="stuno">
        select @@IDENTITY
    </selectKey>
</insert>

    <delete id="delStu">
        DELETE from student where stuno=#{stuno}
    </delete>

    <update id="editStu">
        UPDATE student SET stuname=#{stuname} where stuno=#{stuno}
    </update>

    <select id="findAll" resultType="Student">
        select * from student
    </select>
</mapper>

上面是按MySQL的方式寫的,若是是Oracle的方式的話而oracle則須要使用序列

 

 

MybatisUtil.java

package cn.happyb.util;

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.InputStream;

/**
 * Created by 景佩佩 on 2017-01-19.
 * Mybatis工具類
 */
public class MyBatisUtil {
    private static String config="mybatis-config.xml";
    public static SqlSession getSession() {
             try {
            InputStream stream = Resources.getResourceAsStream(config);
            SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(stream);
            return factory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}

MyTest.java

package cn.happyb;

import cn.happyb.dao.StudentDAOImpl;
import cn.happyb.entity.Student;
import org.junit.Test;

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

/**
 * Created by 景佩佩 on 2017-01-19.
 */
public class FirstTest {
    StudentDAOImpl dao=new StudentDAOImpl();
    @Test
    public  void testAdd(){

            Student stu=new Student();
            stu.setStuname("aa");
            stu.setStudate(new Date());
            stu.setStuage(18);
        System.out.println("添加前====================");
        System.out.println(stu);

        dao.addStu(stu);
        System.out.println("添加前====================");
        System.out.println(stu);

    }

    @Test
    public void delStu() throws IOException{
        dao.delStu(2);
        System.out.print("刪除成功");
    }

    @Test
    public void editStu(){
        Student stu=new Student();
        stu.setStuno(1);
        stu.setStuname("hehe");
        dao.editStu(stu);
        System.out.print("修改爲功");
    }

    @Test
    public void findAll(){
        List<Student> list=dao.findAll();
        for (Student stu:list) {
            System.out.println(stu.getStuname());
        }
    }
}
相關文章
相關標籤/搜索