Integration of CRUD2 mybatis

package com.itheima.dao.impl;

import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 */
public class UserDaoImpl implements IUserDao {

    private SqlSessionFactory factory;

    public UserDaoImpl(SqlSessionFactory factory){
        this.factory = factory;
    }

    @Override 
    public List <the User> the findAll () {
         // 1. The Object Factory acquired SqlSession 
        SqlSession the session = factory.openSession ();
         // 2. SqlSession the calling method, implemented lookup table 
        List <User> users = session. selectList is ( "com.itheima.dao.IUserDao.findAll"); // parameters that can be acquired configuration information Key
         // 3. release resources 
        Session.close ();
         return Users; 
    } 

    @Override 
    public  void saveUser (the User User) {
         // 1. The Object Factory acquired SqlSession 
        SqlSession the session = factory.openSession ();
         //2. Call the method to achieve conservation 
        session.insert ( "com.itheima.dao.IUserDao.saveUser" , the User);
         // 3. commit the transaction 
        Session.commit ();
         // 4. release resources 
        session.close (); 
    } 

    @override 
    public  void the updateUser (the User User) {
         // 1. The Object Factory acquired SqlSession 
        SqlSession the session = factory.openSession ();
         // 2. calls the update method implementation 
        session.update ( "com.itheima.dao.IUserDao.updateUser " , the User);
         // 3. commit the transaction 
        Session.commit ();
         // 4. release resources 
        session.close (); 
    }

    @Override 
    public  void deleteUser (Integer the userId) {
         // 1. The Object Factory acquired SqlSession 
        SqlSession the session = factory.openSession ();
         // 2. calls the Update method implementation 
        session.update ( "com.itheima.dao.IUserDao.deleteUser " , the userId);
         // 3. commit the transaction 
        Session.commit ();
         // 4. release resources 
        Session.close (); 
    } 

    @Override 
    public the User the findById (Integer the userId) {
         // 1. The factory objects acquired SqlSession 
        SqlSession = the session factory.openSession ();
         //2. Call the method SqlSession achieve a query 
        the User the User = session.selectOne ( "com.itheima.dao.IUserDao.findById" , userId);
         // 3. release resources 
        session.close ();
         return the User; 
    } 

    @ override 
    public list <the User> the findByName (String username) {
         // 1. the Object Factory acquired SqlSession 
        SqlSession the session = factory.openSession ();
         // 2. SqlSession the calling method, implemented lookup table 
        list <User> users = session .selectList ( "com.itheima.dao.IUserDao.findByName" , username);
         // 3. release resources 
        session.close ();
         return the Users;
    }

    @Override 
    public  int findTotal () {
         // 1. The Object Factory acquired SqlSession 
        SqlSession the session = factory.openSession ();
         // 2. SqlSession the calling method to achieve a query 
        Integer count = session.selectOne ( "com.itheima .dao.IUserDao.findTotal " );
         // 3. release resources 
        session.close ();
         return COUNT; 
    } 
}

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.itheima.dao.IUserDao">

    <!-- 查询所有 -->
    <select id="findAll" resultType="com.itheima.domain.User">
        select * from user;
    </select>

    <!-- 保存用户 -->
    <insert id="saveUser" parameterType="com.itheima.domain.User">
        <!-- 配置插入操作后,获取插入数据的id -->
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            select last_insert_id();
        </selectKey>
        insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
    </insert>

    <!-- 更新用户 -->
    <update id="updateUser" parameterType="com.itheima.domain.User">
        update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}
    </update>

    <!-- 删除用户-->
    <delete id="deleteUser" parameterType="java.lang.Integer">
        delete from user where id = #{uid}
    </delete>
    
    <!-- 根据id查询用户 -->
    <select id="findById" parameterType="INT" resultType="com.itheima.domain.User">
        select * from user where id =UID} {#
     </ SELECT> 

    <-! fuzzy search based on the name -> 
    <SELECT ID = "the findByName" the parameterType = "String" the resultType = "com.itheima.domain.User"> 
          SELECT * from User like WHERE username {name} #
    </ SELECT> 

    <! - the total number of records acquired user -> 
    <SELECT ID = "findTotal" the resultType = "int"> 
        SELECT COUNT (ID) from user;
     </ SELECT> 
</ Mapper >

sqlconfig

<?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>
    <!--配置环境-->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务 -->
            <transactionManager type="JDBC"></transactionManager>

            <!--配置连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"></property>
                <property name="username" value="root"></property>
                <property name="password" value="1234"></property>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置映射文件的位置 -->
    <mappers>
        <mapper resource="com/itheima/dao/IUserDao.xml"></mapper>
    </mappers>
</configuration>

test

package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.dao.impl.UserDaoImpl;
import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

/**
 * @author 黑马程序员
 @Company * http://www.ithiema.com 
 * 
 * mybatis test operation of crud 
 * / 
public  class MybatisTest { 

    Private the InputStream in;
     Private IUserDao userDao; 

    @Before // for performing the method is performed prior to the test 
    public  void the init () throws Exception {
         // 1. reads the configuration file to generate an input stream of bytes 
        in Resources.getResourceAsStream = ( "the SqlMapConfig.xml" );
         // 2. Get a SqlSessionFactory 
        a SqlSessionFactory Factory = new new the SqlSessionFactoryBuilder () Build (in);.
         / / 3. use the factory object, create an object dao
        = userDao new new UserDaoImpl (Factory); 
    } 

    @After // for performing the method is performed after the test 
    public  void the destroy () throws Exception {
         // 6. The release resources 
        in.close (); 
    } 

    / ** 
     * Search Test 
     * / 
    @Test 
    public  void testFindAll () {
         // 5. The method of performing Search 
        List <the User> Users = userDao.findAll ();
         for (the User User: Users) { 
            System.out.println (User); 
        } 

    } 
    / * * 
     * test the save operation 
     * / 
    @Test
    public  void testSave () { 
        the User User = new new the User (); 
        user.setUsername ( "impl User DAO" ); 
        user.setAddress ( "Shunyi region" ); 
        user.setSex ( "M" ); 
        user.setBirthday ( new new a Date ()); 
        System.out.println ( "before the save operation:" + User);
         // 5. The method for storing execution 
        userDAO.saveUser (User); 

        System.out.println ( "after a save operation:" + User ); 
    } 

    / ** 
     * test update 
     * / 
    @Test 
    public  voidtestUpdate () { 
        the User User = new new the User (); 
        user.setId ( 50 ); 
        user.setUsername ( "UserDAOImpl Update User" ); 
        user.setAddress ( "Shunyi region" ); 
        user.setSex ( "F" ); 
        User .setBirthday ( new new a Date ()); 

        // 5. The method for storing execution 
        userDao.updateUser (User); 
    } 

    / ** 
     * delete test 
     * / 
    @Test 
    public  void TestDelete () {
         // 5. The delete method 
        userDao. deleteUser (54 is ); 
    } 

    / ** 
     * test deletion
     * /
    @Test 
    public  void testFindOne () {
         // 5. The method of performing a query 
        the User User = userDao.findById (50 ); 
        System.out.println (User); 
    } 

    / ** 
     * Test Fuzzy query 
     * / 
    @Test 
    public  void testFindByName () {
         // 5. The method of performing a query 
        List <User> users = userDao.findByName ( "% King%" );
         for (the User User: Users) { 
            System.out.println (User); 
        } 
    } 

    / * * 
     * total number of test records query 
     * / 
    @Test 
    public  voidtestFindTotal () {
        // 5. The method of performing a query 
        int COUNT = userDao.findTotal (); 
        System.out.println (COUNT); 
    } 



}

pom

<?xml version="1.0" encoding="UTF-8"?>
<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.itheima</groupId>
    <artifactId>day02_eesy_02mybatsiDAO</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

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

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>

</project>

 

Guess you like

Origin www.cnblogs.com/yangshuyuan1009/p/11482141.html