Mybatis BASICS (2) ---- development of the original dao and mapper proxy, mybatismapper

Source: Internet
Author: User

Mybatis BASICS (2) ---- development of the original dao and mapper proxy, mybatismapper

Undertake the previous mybatis entry-level BASICS (1)

After reading the previous article, I can see that there are a lot of repeated code in MybatisService, which does not seem very clear, but the first time I write it like that, I want to know how to execute mybatis, bitter before sweet!

I. Original dao Development Method

Summary: 1. Compile the dao interface and dao implementation class in the box price set up in the previous article.

2. Inject SqlSessionFactory into the dao interface implementation class and create sqlSession through SqlSessionFactory in the method body.

  • DAO Interface Class UserDAO. java
Package com. mybatis. dao; import java. util. list; import com. mybatis. entity. user;/***** @ ClassName: UserDAO * @ Description: TODO (User management DAO Interface) * @ author warcaft * @ date 10:23:42 **/public interface UserDAO {/** query User information by ID */public User findUserById (Integer id ); /** fuzzy query of User information by User name */public List <user> findUserByName (String username);/** Add User */public void insertUser (User user ); /** delete User by ID */public void deleteUser (Integer id);/** update user by ID */public void updateUser (User user User );}
  • Dao implementation class UserDaoImpl. java
Package com. mybatis. dao; import java. util. list; import org. apache. ibatis. session. sqlSession; import org. apache. ibatis. session. sqlSessionFactory; import com. mybatis. entity. user;/***** @ ClassName: UserDaoImpl * @ Description: TODO (Implementation class of the User management interface) * @ author warcaft * @ date 2015-6-27 10:29:35 */public class UserDaoImpl implements UserDAO {private SqlSessionFactory sqlSessionFactory; // SqlSessionFactory needs to be injected into dao implementation class // public UserDaoImpl (SqlSessionFactory sqlSessionFactory) {this. sqlSessionFactory = sqlSessionFactory;} @ Override public User findUserById (Integer id) {SqlSession sqlSession = sqlSessionFactory. openSession (); User user = sqlSession. selectOne ("test. findUserById ", id); // release the resource sqlSession. close (); return user ;}@ Override public List <User> findUserByName (String username) {SqlSession sqlSession = sqlSessionFactory. openSession (); List <User> list = sqlSession. selectList ("test. findUserByName ", username); // submit the sqlSession transaction. commit (); // releases the resource sqlSession. close (); return list ;}@ Override public void insertUser (User user) {SqlSession sqlSession = sqlSessionFactory. openSession (); // execute the insert operation sqlSession. insert ("test. insertUser ", user); // submit the sqlSession transaction. commit (); // releases the resource sqlSession. close () ;}@ Override public void deleteUser (Integer id) {SqlSession sqlSession = sqlSessionFactory. openSession (); // execute the insert operation sqlSession. delete ("test. deleteUser ", id); // submit the sqlSession transaction. commit (); // releases the resource sqlSession. close () ;}@ Override public void updateUser (User user User) {SqlSession sqlSession = sqlSessionFactory. openSession (); // execute the insert operation sqlSession. update ("test. updateUser ", user); // submit the sqlSession transaction. commit (); // releases the resource sqlSession. close ();}}
  • JunitTest test UserDaoImplTest. java
Package com. mybatis. dao. test; import java. io. inputStream; import java. util. date; import java. util. list; import org. apache. ibatis. io. resources; import org. apache. ibatis. session. sqlSessionFactory; import org. apache. ibatis. session. sqlSessionFactoryBuilder; import org. junit. before; import org. junit. test; import com. mybatis. dao. userDaoImpl; import com. mybatis. entity. user; public class UserDaoImplTest {private SqlSessionFactory sqlSessionFactory; @ Before public void setUp () throws Exception {String resource = "SqlMapConfig. xml "; InputStream inputStream = Resources. getResourceAsStream (resource); sqlSessionFactory = new SqlSessionFactoryBuilder (). build (inputStream) ;}@ Test public void findUserByIdTest () {UserDaoImpl userDao = new UserDaoImpl (sqlSessionFactory); User user = userDao. findUserById (1); System. out. println (user) ;}@ Test public void findUserByNameTest () {UserDaoImpl userDao = new UserDaoImpl (sqlSessionFactory); List <User> list = userDao. findUserByName ("small"); System. out. println (list) ;}@ Test public void insertUserTest () {UserDaoImpl userDao = new UserDaoImpl (sqlSessionFactory); User user = new User (); user. setUsername ("Zhang Sanfeng"); user. setSex ("1"); user. setBirthday (new Date (); user. setAddress ("Wudang Mountains"); userDao. insertUser (user) ;}@ Test public void deleteUserTest () {UserDaoImpl userDao = new UserDaoImpl (sqlSessionFactory); userDao. deleteUser (8) ;}@ Test public void updateUserTest () {UserDaoImpl userDao = new UserDaoImpl (sqlSessionFactory); User user = new User (); user. setId (1); user. setUsername (""); user. setSex ("2"); user. setAddress ("Tianjin"); user. setBirthday (new Date (); userDao. updateUser (user );}}

The above Code shows that the content in the MybatisService. java class is a little clearer. However, the following problems still exist:

1. There are a lot of template methods in the dao interface. Can we put forward these codes to reduce our workload?

2. The statement id is hardcoded when the sqlSession method is called.

3. Call the variables passed in by sqlSession. Because the sqlSession method uses generics, no error is reported during compilation even if the variable type is incorrect. This is not conducive to program development.

So let's take a look at the mapper proxy development methods with these questions. Can these problems be solved?

Ii. mapper proxy method (only the mapper interface is required, which is equivalent to the dao Interface)

1. Summary:(1) Compile the XXXmapper. xml ing file.

(2) Writing mapper interfaces must follow some development specifications. mybatis can automatically generate mapper interfaces to implement class proxy objects.

2. Development specifications:

(1). In XXXmapper. xml, namespace is equal to the mapper interface address;

  

(2) The method in. XXXmapper. java interface is consistent with the statement Id in ER er. xml.

(3) The method input parameter in the mapper. java interface is the same as the type specified by statement parameterType in mapper. xml.

(4) The type of the return value of the method in the mapper. java interface is the same as the type specified by the resultType of statement in mapper. xml.

  

  

Summary: The above development specifications mainly generate the following code in a unified manner.

    SqlSession sqlSession = sqlSessionFactory.openSession();    User user = sqlSession.selectOne("test.findUserById", id);
  ......

3. UserMapper. java code

Package com. mybatis. mapper; import java. util. list; import com. mybatis. entity. user;/***** @ ClassName: UserDAO * @ Description: TODO (User management er ER interface) * @ author warcaft * @ date 10:23:42 **/public interface UserMapper {/** query User information by ID */public User findUserById (int id ); /** fuzzy query of User information by User name */public List <user> findUserByName (String username);/** Add User */public void insertUser (User user ); /** delete User by ID */public void deleteUser (Integer id);/** update user by ID */public void updateUser (User user User );}View Code

4. Copy the original User. xml file and change it to UserMapper. xml. You only need to modify this line of code.

<! -- Namespace is used to classify and manage SQL statements. It is understood as SQL isolation. Note: namespace has a special role when developing with mapper agents, namespace is equal to the mapper interface address --> <mapper namespace = "com. mybatis. mapper. userMapper ">

5. Load UserMapper. xml in SqlMapConfig. xml

<! -- Load the ing file --> <mappers> <mapper resource = "sqlmap/User. xml"/> <mapper resource = "mapper/UserMapper. xml"/> </mappers>

6. Junit test UserMapperTest. java

Package com. mybatis. dao. test; import java. io. inputStream; import java. util. date; import java. util. list; 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. before; import org. junit. test; import com. mybatis. entity. user; import com. mybatis. mapper. userMapper; public class UserMapperTest {private SqlSessionFactory sqlSessionFactory; // This method is run @ Before public void setUp () throws Exception {String resource = "SqlMapConfig. xml "; InputStream inputStream = Resources. getResourceAsStream (resource); // create SqlSessionFcatory sqlSessionFactory = new SqlSessionFactoryBuilder (). build (inputStream) ;}@ Test public void testFindUserById () {SqlSession sqlSession = sqlSessionFactory. openSession (); // create a Usermapper object. mybatis automatically generates the mapper proxy object UserMapper mapper = sqlSession. getMapper (UserMapper. class); User user = mapper. findUserById (1); System. out. println (user); sqlSession. close () ;}@ Test public void testFindUserByName () {SqlSession sqlSession = sqlSessionFactory. openSession (); // create a Usermapper object. mybatis automatically generates the mapper proxy object UserMapper mapper = sqlSession. getMapper (UserMapper. class); List <User> list = mapper. findUserByName ("small"); System. out. println (list); sqlSession. close () ;}@ Test public void testDeleteUser () {SqlSession sqlSession = sqlSessionFactory. openSession (); // create a Usermapper object. mybatis automatically generates the mapper proxy object UserMapper mapper = sqlSession. getMapper (UserMapper. class); mapper. deleteUser (6); sqlSession. commit (); sqlSession. close () ;}@ Test public void testInsertUser () {SqlSession sqlSession = sqlSessionFactory. openSession (); // create the Usermapper object. mybatis automatically generates the mapper proxy Object User = new user (); User. setUsername ("Others"); user. setSex ("1"); user. setAddress ("Mongolia qiyan tribe"); user. setBirthday (new Date (); UserMapper mapper = sqlSession. getMapper (UserMapper. class); mapper. insertUser (user); sqlSession. commit (); sqlSession. close () ;}@ Test public void testUpdateUser () {SqlSession sqlSession = sqlSessionFactory. openSession (); // create the Usermapper object. mybatis automatically generates the mapper proxy Object User = new user (); User. setId (11); // The Id user must be set. setUsername ("swordsman"); user. setSex ("1"); user. setAddress ("Mongolia qiyan tribe"); user. setBirthday (new Date (); UserMapper mapper = sqlSession. getMapper (UserMapper. class); mapper. updateUser (user); sqlSession. commit (); sqlSession. close ();}}View Code

7. Summary

(1 ). inside the proxy object, selectOne () and selectList () are called: If the mapper object returns a single pojo object (not a collection object), the proxy object internally queries the database through selectOne. If the mapper method returns the collection object, the proxy object internally queries the database through selectList.

(2). Only one method parameter in the mapper interface can affect system development:

The mapper interface can have only one method parameter. Is the system not conducive to maintenance?

A: In the system framework, the dao Layer Code is shared by the business layer. The mapper interface has only one parameter. pojo of the packaging type can be used to meet the needs of different business methods.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.