1. 程式人生 > >Mybatis實現資料的增刪改查

Mybatis實現資料的增刪改查

首先在pom.xml中加入依賴

       
         <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- 不寫版本號會識別不出SqlSessionFactory-->

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

 然後在resource中建立一個Configuration.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>
   <!-- mybatis別名定義  alias別名名稱,用package的別名就是包下實體類的名稱-->
       <!--第二種方法更好-->

     <typeAliases>
       <!--<typeAlias type="com.lixin.mybatis.User" alias="User"/>-->
        <package name="com.lixin.mybatis"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
                <property name="username" value="root"/>
                <property name="password" value="115600LX"/>
            </dataSource>
        </environment>
    </environments>

    <!-- mybatis的mapper檔案,每個xml配置檔案對應一個介面 -->
    <mappers>
        <!-- 註冊自定義的對映檔案 -->
        <mapper resource="mappers/user.xml"/>
    </mappers>
</configuration>

建立實體類User

package com.lixin.mybatis;

public class User {
    private int id;
    private String username;
    private int sex;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex=" + sex +
                ", age=" + age +
                '}';
    }
}

建立resource-mappers-user.xml實現對資料的增刪改查(對映檔案)

在mybatis中,對映檔案中的namespace是用於繫結Dao介面的,即面向介面程式設計。-------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">

<!-- 使用介面方式 載入名稱空間 使用代理模式 -->
<mapper namespace="com.lixin.mybatis.IUserOperaton">

    
    <select id="findUserById" parameterType="int"  resultType="User">
        SELECT * FROM user1 WHERE id = #{id}
    </select>

    <select id="findAllUser" resultType="User">
        SELECT * FROM user1;
    </select>

    <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into user1(id,username,sex,age) values (#{id},#{username},#{sex},#{age})
    </insert>

    <delete id="deleteUser" parameterType="int">
        delete from user1 where id=#{id}
    </delete>
</mapper>

建立介面類IUserOperation

IUserOperation為操作介面,函式名和mybatis的xml配置檔案中的操作id名對應。

package com.lixin.mybatis;

import java.util.List;

public interface IUserOperaton {
    public User findUserById(int id);

    public List<User>findAllUser();

    public void addUser(User user);

    public void deleteUser(int id);
}

編寫Mybatis工具類Util

用靜態程式碼塊進行建立SqlSessionFactory,只在類載入時建立一次,保證了整個程式執行時只有一個工廠例項。

package com.lixin.mybatis;
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.InputStream;
import java.io.Reader;
import java.util.List;

public class Util {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;
    private User user;
    private static int Ret;

    //從xml中獲取sqlSessionFactory
    // 建立sqlSessionFactory物件,因為整個應用程式只需要一個例項物件,故用靜態程式碼塊
    static {
        try {
            Reader reader = Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            SqlSession session = sqlSessionFactory.openSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //返回SessionFactory
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    //返回Session;
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }

  /*
       isAutoCommit:
       true 表示建立的SqlSession物件在執行完SQL之後會自動提交事務
       false 表示建立的SqlSession物件在執行完SQL之後不會自動提交事務,這時就需要我們手動呼叫sqlSession.commit()
   */
  public static SqlSession getSqlSession(boolean isAutoCommit) {
      return getSqlSessionFactory().openSession(isAutoCommit);
  }

}

測試類--Test

package com.lixin.mybatis;

import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public void findAllUsers(){
        SqlSession sqlSession =Util.getSqlSession(true);
        IUserOperaton usermapper=sqlSession .getMapper(IUserOperaton.class);
        List<User>users=usermapper .findAllUser() ;
        for(User u:users ){
            System.out .println("ID:"+u.getId() +";Usernamr:"+u.getUsername() +";Sex:"+u.getSex() +";Age:"+u.getAge() );
        }
        sqlSession .close() ;
    }

    public void addUser(){
        SqlSession sqlSession =Util.getSqlSession(true);
        IUserOperaton usermapper=sqlSession .getMapper(IUserOperaton.class);
        User newuser =new User() ;
        newuser .setUsername("李鑫");
        newuser .setAge(18);
        newuser.setSex(2);
        usermapper.addUser(newuser );
        sqlSession .close() ;
    }

    public void deleteUser(int id){
        SqlSession sqlSession =Util.getSqlSession(true);
        IUserOperaton usermapper=sqlSession .getMapper(IUserOperaton.class);
        usermapper .deleteUser(id);
        sqlSession .close() ;
    }


    public void updateUser(){
        SqlSession sqlSession =Util.getSqlSession(true);
        IUserOperaton usermapper=sqlSession .getMapper(IUserOperaton.class);
        User newuser=new User() ;
        newuser.setId(1);
        newuser .setSex(1) ;
        newuser .setUsername("秦鬆");
        newuser .setAge(22);
        usermapper .updateUser(newuser );
        sqlSession .close() ;


    }
}

主函式

package com.lixin.mybatis;

import org.apache.ibatis.session.SqlSession;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@SpringBootApplication
public class MybatisApplication {
    public static void main(String[] args) {
        Test test=new Test() ;
        test.findAllUsers() ;//查詢所有User
        test.addUser() ;//新增User
        test.deleteUser(3);//根據id號刪除User
        test.updateUser() ;//更新User資訊
    }
}