Mybatis增刪改查實例

一.什麼是MyBatis
MyBatis 是支持定製化 SQL、存儲過程以及高級映射的優秀的持久層框架。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 可以對配置和原生Map使用簡單的 XML 或註解,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。
二.創建數據庫表

  create table student (id integer primary key auto_increment, name varchar(100), sex varchar(100), hobby varchar(200));

    insert into student values(null, 'zhangsan','male','吃吃吃');
    insert into student values(null, 'lisi', 'female','玩玩玩');

三.配置pom.xml(用的maven創建的)需要加入依賴

<!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>

    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.35</version>
    </dependency>
    <dependency>
還需要在build 下面加入
<resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.tld</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.tld</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>

四.這裏寫圖片描述

五.配置baits-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>

    <properties resource="db.properties"/>



    <!--別名-->
    <typeAliases>
        <!--將這個包下面的對應的類別名設置爲類名-->
        <!--下面這個寫你的bean名字-->
        <package name="com.xxx.bean"/>
    </typeAliases>

    <!--這是mybatis 的配置文件
    如果單獨使用mybatis,必須寫這個文件
    如果和spring 使用,不需要這個文件
    這個裏面所有的都是有順序的-->
<environments default="deve">
    <!--這個environments 標籤下可以配置很多歌environment 標籤
    使用default 屬性來確定當前使用的是哪個environment-->
    <environment id="deve">
        <!--事務管理器-->
        <transactionManager type="JDBC"></transactionManager>
        <!--連接池-->
        <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.xml-->
        <!--下面這個寫你的mapper名字-->
        <package name="com.xxx.mapper"/>
    </mappers>
</configuration>

六.studentMapper

//1.創建一個xxx的Mapper的接口文件
public interface StudentMapper {

    List<Student> findAllStudent();

    //帶參數的batis方法的寫法
    //Student findAllStudentById(Integer id);
    Student findAllStudentById(@Param("uid") Integer id);
    //增加一條數據
    void insertNewStudent(@Param("name") String name,
                          @Param("sex") String sex,
                          @Param("hobby") String hobby);
    //實體類的方式增加
    void insertStu(Student student);

    void deleteById(@Param("uid") Integer id);

    void  updateStudent(Student student);
}

七.StudentMapper.xml (最好和你上邊的mapper名字對應)

<?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">
<!--用namespace 來配置 當前接口,所有的實現都在xml中寫,不會創建一個類來實現-->
<mapper namespace="com.xxx.mapper.StudentMapper">
    <!--結果映射
    作用:把數據庫的列名 和實體類的屬性名關聯起來-->
    <resultMap id="BaseMap" type="Student">
        <!--把數據庫中的id 賦值給了實體類的id-->
        <id column="id" property="id"/>
        <result column="name" property="name" javaType="String" jdbcType="VARCHAR"/>
        <result column="sex" property="sex" javaType="String" jdbcType="VARCHAR"/>
        <result column="hobby" property="hobby" javaType="String" jdbcType="VARCHAR"/>
    </resultMap>
    <!--可以封裝一段比較固定的sql 語句.方便後續的debug-->
    <sql id="Base-sql">
        id,name,sex,hobby
    </sql>

    <!--select 的id 是你的方法名字 -->
    <select id="findAllStudent" resultMap="BaseMap">
        SELECT
         <include refid="Base-sql"/>
         FROM  student
    </select>
    <select id="findAllStudentById" resultMap="BaseMap" parameterType="Integer">
        SELECT * FROM student WHERE id=#{uid}

    </select>
<insert id="insertNewStudent" >
    INSERT  INTO student VALUES (NULL ,#{name},#{sex},#{hobby})

</insert>
    <!--塞進實體類 ,最好寫paramType 告訴他參數是一個實體類
    keyProperty 就是你塞完數據,會把這個id 幫你保存到這個裏面-->
    <insert id="insertStu" useGeneratedKeys="true" keyProperty="id" parameterType="com.xxx.bean.Student">
        INSERT  INTO student VALUES (NULL ,#{name},#{sex},#{hobby})
    </insert>

    <delete id="deleteById" >
        DELETE FROM student WHERE id=#{uid}
    </delete>

    <update id="updateStudent" parameterType="com.xxx.bean.Student">
        UPDATE student SET  name=#{name} ,sex=#{sex} ,hobby=#{hobby} WHERE id=#{id}
    </update>

</mapper>

八.db.propertise
這裏寫圖片描述

九.輸出

public class BatisTest {
    @Test
    public void test1() throws IOException {

        //1. 配置mapper

        //2. 讀取config 文件

        //除了select 其他的都需要提交事務

        InputStream stream = Resources.getResourceAsStream("batis-config.xml");
        //創建session工廠
        SqlSessionFactory factory=
                new SqlSessionFactoryBuilder().build(stream);
        //打開一個session
        SqlSession sqlSession=factory.openSession();

        //使用session 讀取一個mapper 對象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //調用findAllStudent方法
//        List<Student> allStudent = mapper.findAllStudent();
//        Student student = mapper.findAllStudentById(1);
//        System.out.println(allStudent);
//        System.out.println(student);


//        Student student=new Student();
//        student.setName("zhangwu");
//        student.setSex("男");
//        student.setHobby("睡覺");
//        mapper.insertNewStudent(student.getName(),student.getSex(),student.getHobby());
//        sqlSession.commit();

            //這個是增加一個實體類
        Student student=new Student();
        student.setName("曾小賢11");
        student.setSex("男");
        student.setHobby("睡覺");
        mapper.insertStu(student);
        sqlSession.commit();

//        mapper.deleteById(5);
//        sqlSession.commit();

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章