MyBatis入门案例、增删改查

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

   MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis,实质上Mybatis对ibatis进行一些改进。 

  MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。

  Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。

MyBatis入门案例:

1.pox.xmljar包

 

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

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

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

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.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="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());
        }
    }
}

 

posted @ 2017-01-22 11:25  Monodrama  阅读(783)  评论(3编辑  收藏  举报