Mybatis learning day2

Preliminary Mybatis

 

Previously achieved by the use of mybatis link database queries for all users information (use the resources in the establishment and Dao layer to achieve the same directory xml ). Then look at the additions and deletions to change search other operations and so on.

We can not use Mybatis write Dao implementation class layer. Let proxy object to help us do it.

 

Notes ways: not only as servlet and can be configured through the xml can also use annotations. Below the main display annotations ways.

: UserDao directly in the interface (do not know the layout of the document can first see here https://www.cnblogs.com/cstdio1/p/11882953.html writing Sql statement under)

Before we talk about a class test functions are built in this Test inside the unit test

unit test:

 

You must be configured to use in pom.xml:

 

  

Search:

 

 

Unit test code:

 

 Careful partner may have found this little test code how such a short period, obviously the last few steps with Mybatis have it.

In fact, we will be a few steps that package, written in two functions, one for (After) calls before and after the test (Before) and a test call.

With annotations @Before and @After

before testing:

 

 After the test:

 

 

After the operation is probably also true, do not want to ramble on *, there is little need to say something.

Sometimes the argument passed is not a simple type but a class object, this time we need to write the corresponding class attribute (and final information can be found by this query object properties)

The simplest case is that this class has indirectly User type attribute is the type to look for

E.g:

 

The above is a variable user class Query (User type) .username then be used directly by user, username is an attribute of the User class

Internal Query:

 

 

SQL statements executed (placeholder way):

search result:

 

 Another way is to:

 

 Execute SQL statements (SQL injection):

 

 search result:

 

 Because Sql 'Therefore, the general problem is injected with a first embodiment

 

UserDao Source:

package com.zyb.dao;

import com.zyb.pojo.Query;
import com.zyb.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserDao {
    /**
     * 查询所有用户
     * @return
     */
    @Select("select * from my_user")
    List<User> selAll();


    /**
     * 保存方法
     */
    @Insert("insert into my_user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
    void saveUser(User user);

    / ** 
     * update 
     * / 
    @Update ( "SET Update my_user username = # {} username, address address = # {}, {Sex Sex = #}, {Birthday Birthday = #} # {WHERE ID = ID}" )
     void updateUser (the User the User); 


    / ** 
     * delete records by the above mentioned id 
     * @param 
     * / 
    @Delete ( "the delete from the above mentioned id my_user the WHERE uid = # {}") // can not call uid, just from the name of the 
    void deleUserById ( userId Integer); 

    / ** 
     * according to the query id 
     * @param userId 
     * @return 
     * / 
    the @Select ( "the SELECT * from my_user the WHERE id uid = # {}") // can not call uid, just from the name
    SelById the User (Integer the userId); 

    / ** 
     * Fuzzy queries by name 
     * @return 
     * / 
    // @Select ( "SELECT * WHERE from my_user like username # {name}") // this way need to increase outside% 
    @ SELECT ( "SELECT * wHERE username from my_user like '% $ {value}%'") // do not need to increase outside%, where the variable name must be a value 

    List <the User> selByName (String the userName); 

    / ** 
     * query the total number of users 
     * @return 
     * / 
    @Select ( "SELECT COUNT (ID) from my_user") // aggregate functions 
    int selUserNums (); 

    / ** 
     * last inserted query video ID 
     * @return 
     * /
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", keyColumn = "id", before = false, resultType = int.class)
    int selLastInsertId();

    /**
     * 根据Query的信息查询用户
     * @param query
     * @return
     */
    @Select("select * from my_user where username like #{user.username}")
    List<User> selByQuery_UserName(Query query);
}

Test category Source:

package com.zyb.test;

import com.zyb.dao.UserDao;
import com.zyb.pojo.Query;
import com.zyb.pojo.User;
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 org.junit.After;
import org.junit.Before;

import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;
import java.util.Date;
importjava.util.List; 

public  class the Test { 
    the InputStream in; 
    the SqlSession the session; 
    UserDao userDao; 

    @Before 
    public  void the init () throws IOException {
         // 1. reads the configuration file 
        in Resources.getResourceAsStream = ( "the SqlMapConfig.xml" );
         // 2. create SqlSessionFactory plant 
        the SqlSessionFactoryBuilder Builder = new new the SqlSessionFactoryBuilder (); 
        SqlSessionFactory factory's = builder.build (in);
         // 3. use an object factory production SqlSession 
        the session = factory.openSession ();
        // 4. Create SqlSession Dao interface proxy object 
        userDao = session.getMapper (UserDao. Class ); 
    } 

    @After 
    public  void Destory () throws IOException { 
        Session.commit (); 
        // 6. The release resources 
        Session.close ( ); 
        in.close (); 

    } 


    / ** 
     * Search test 
     * @throws IOException
      * / 
    @ org.junit.Test 
    public  void testSelAll () throws IOException { 

        // 5. The use of a proxy object execution method 
        List <User> users = userDao.selAll ();
        for (the User User: Users) { 
            System.out.println (User); 
        } 


    } 

    / ** 
     * save operation test 
     * @throws IOException
      * / 
    @ org.junit.Test 
    public  void testSave () throws IOException { 

        the User User = new new the User (); 
        user.setAddress ( "Chengdu" ); 
        user.setBirthday ( new new a Date ()); 
        user.setSex ( "M" ); 
        user.setUsername ( "ZS" ); 

        // 5. The use of a proxy object to perform method
        userDAO.saveUser (User); 


    } 

    / ** 
     * test update 
     * / 
    @ org.junit.Test 
    public  void testUpdate () { 
        the User User = new new the User (); 
        user.setAddress ( "Chengdu" ); 
        user.setBirthday ( new new a Date ()); 
        user.setSex ( "F" ); 
        user.setUsername ( "ZJ" ); 
        user.setId ( 51 is ); 
        userDao.updateUser (User); 



    } 

    / ** 
     * delete test 
     * / 
    @ org.junit.Test 
    public  voidtestDel () { 
        Integer ID = new new Integer (51 is ); 
        userDao.deleUserById (ID); 
    } 

    @ org.junit.Test 

    / ** 
     * Test query 
     * / 
    public  void testSelOne () { 
      the User User = userDao.selById (48 ); 
        System.out.println (User); 
    } 

    / ** 
     * test fuzzy search 
     * / 
    @ org.junit.Test 
    public  void testSelByName () { 
     List <the User> Users = userDao.selByName ( "King" ); 
     Users. forEach (X -> System.out.println (X)); 

    } 

    / **
     * Test Total number of users 
     * / 
    @ org.junit.Test 
    public  void testSelUserNums () { 
        System.out.println ( "total number of users is:" + userDao.selUserNums ()); 
    } 

    @ org.junit.Test 
    public  void testSelByQuery ( ) { 
        query query = new new query (); 
        the User User = new new the User (); 
        user.setUsername ( "King%%"); // Fuzzy query 
        query.setUser (User); 
        List <the User> Users = userDao.selByQuery_UserName ( Query); 
        users.forEach (X -> System.out.println (X)); 
    } 



}

 

 

Guess you like

Origin www.cnblogs.com/cstdio1/p/11892429.html