MyBatis sql mapper Mapper

getting Started

  MyBatis based on dynamic proxy mechanism, so that we no longer need to write Dao achieve.

  Traditional Dao interface name is now unified with Mapper end , and our mapper and mapper configuration files to be in the same package . :

 

   IDeptDao ----> DeptMapper.java --- DeptMapper.xml (namespace to write directly DeptMapper.java fully qualified name )

 

 

1. Create a User class (Start with a table in the database is User, and there are corresponding field)

public  class the User {
     Private Long ID;
     Private String name; 

   GET and set and tostring omitted herein. . . . ( GET and tostring and set to, and not too long copy ) } 

2. a top class built interfaces UserMapper

import java.util.List;
/ ** 
* query the database for all data
* @return
* /
public interface UserMapper { 
  List
<User> queryAll();
}

 

3. Build a UserMapper.xml

 

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
<! DOCTYPE Mapper the PUBLIC "- // mybatis.org//DTD Mapper 3.0 // EN" 
        "http://mybatis.org/dtd/mybatis mapper.dtd--3 " > 
<-! ORM framework sql mapping 
namespace: namespace namespace path + id value 
          how namespace configuration package name interface name queryAll +. 
-> 
< Mapper namespace =" cn.itsource._02mapper. UserMapper " >
<-! Query queryAll () 
resultType return type of
attention to the following id values must interface and method names you agree, if they have one to one other method, otherwise it will error method can not find
     the value of what you perform the following resultType sql statement returns the following data types

->
<select id="queryAll" resultType="User"> select * from t_user </select> 

</mapper>

 

 

 

 

4. Write a class test test

Import org.apache.ibatis.session.SqlSession;
 Import org.junit.Test;
 Import util.MyBataisUtil; 

Import java.util.List; 

public  class UserImplTest { 

    @Test 
    public  void querAll () {
         // MyBataisUtil.MYBATAIS.getSqlSession ( ); single package embodiment mode good SQLSESSION 
        the SqlSession SQLSESSION = MyBataisUtil.MYBATAIS.getSqlSession ();
         // sqlSession.getMapper (for dynamic proxy interface) to return a dynamic proxy class 
        UserMapper Mapper = sqlSession.getMapper (UserMapper. class );
         // dynamic proxy class to call all the data query method 
        List <User> users = mapper.queryAll();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/bigbigxiao/p/11946534.html