Spring + SpringMVC + MyBatis deep learning and building (2) -- MyBatis original Dao development and mapper Agent Development, springmvcmybatis

Source: Internet
Author: User

Spring + SpringMVC + MyBatis deep learning and building (2) -- MyBatis original Dao development and mapper Agent Development, springmvcmybatis

Reprinted please indicate the source: http://www.cnblogs.com/Joanna-Yan/p/6869133.html

I have written Spring + SpringMVC + MyBatis for deep learning and building (I)-basic knowledge of MyBatis. There are a lot of repeated code in MybatisFirst. The code is simplified this time:

There are two methods to develop Dao using MyBatis: the original Dao development method and the Mapper interface development method.

1. SqlSession usage scope

1.1 SqlsessionFactoryBuilder

Use SqlSessionFactoryBuilder to create a session factory SqlSessionFactory and use SqlSessionFactoryBuilder as a tool class. You do not need to use a single instance to manage SqlSessionFactoryBuilder.

To create SqlSessionFactory, you only need to create a new SqlSessionFactoryBuilder.

1.2 SqlsessionFactory

Use SqlSessionFactory to create a SqlSession and use the singleton mode to manage SqlSessionFactory (once a factory is created, an instance is used ).

After MyBatis and Spring are integrated in the future, use the singleton mode to manage SqlSessionFactory.

1.3 SqlSession

SqlSession is an interface for users (programmers.

SqlSession provides many database operations methods, such as selectOne (returning a single object) and selectList (returning a single or multiple objects ).

SqlSession is thread-insecure. In the SqlSession implementation class, besides methods in the interface (methods used to operate databases) and data domain attributes.

SqlSession is best used in methods and defined as local variables.

2. Original dao development method (the programmer needs to write the dao interface and dao implementation class) 2.1 ideas

The programmer needs to write the dao interface and dao implementation class.

You need to inject SqlSessionFactory into the dao implementation class and create SqlSession in the method body through SqlSessionFactory.

2.2 dao Interface
Public interface UserDao {// query User information by id public User findUserById (int id) throws Exception; // Add user Information public void insertUser (User) throws Exception; // Delete the user information public void deleteUser (int id) throws Exception ;}
2.3 dao interface implementation class
Public class UserDaoImpl implements UserDao {// SqlSessionFactory needs to be injected into dao implementation class // here private SqlSessionFactory sqlSessionFactory is injected through the constructor; public UserDaoImpl (SqlSessionFactory sqlSessionFactory) {super (); this. sqlSessionFactory = sqlSessionFactory;} @ Override public User findUserById (int id) throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); User user = sqlSession. selectOne ("test. findUserById ", id); // release the resource sqlSession. close (); return user ;}@ Override public void insertUser (User user) throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); sqlSession. insert ("test. insertUser ", user); // submit the sqlSession transaction. commit (); // releases the resource sqlSession. close () ;}@ Override public void deleteUser (int id) throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); sqlSession. delete ("test. deleteUser ", id); // submit the sqlSession transaction. commit (); // releases the resource sqlSession. close ();}}
2.4 Test code
Public class UserDaoImplTest {private SqlSessionFactory sqlSessionFactory; @ Before public void setUp () throws IOException {// create sqlSessionFactory // mybatis configuration file String resource = "SqlMapConfig. xml "; // get the configuration file stream InputStream inputStream = Resources. getResourceAsStream (resource); // create a session factory and input the configuration file information of mybatis sqlSessionFactory = new SqlSessionFactoryBuilder (). build (inputStream) ;}@ Test public void findUserByIdTest () throws Exception {UserDao userDao = new UserDaoImpl (sqlSessionFactory); User user = userDao. findUserById (1); System. out. println (user );}}
2.5 Summary of original dao development issues

(1) There are a large number of template methods in dao interface implementation class methods. Imagine whether the code can be extracted, greatly reducing the workload of programmers.

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

(3) variables passed in when the sqlSession method is called. Because the sqlSession method uses generics, no errors are reported during compilation even if the variable type is incorrect, which is not conducive to programmer development.

3. mapper proxy method (the programmer only needs to write the mapper interface (equivalent to the dao Interface )) 3.1 ideas (er proxy development specifications)

Programmers need to write mapper. xml ing files

Programmers must follow some development specifications to write mapper interfaces. mybatis can automatically generate mapper interfaces to implement class proxy objects.

Development specifications:

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

(2) The method name in the mapper. java interface is the same as the statement id in mapper. xml.

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

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

Summary:

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

User user = sqlSession.selectOne("test.findUserById", id);sqlSession.insert("test.insertUser", user);......
3.2 mapper. java
Package joanna. yan. mybatis. mapper; import java. util. list; import joanna. yan. mybatis. entity. user;/*** is equivalent to dao interface * @ author Joanna. yan **/public interface UserMapper {// query User information by id public User findUserById (int id) throws Exception; // query the User's public List by name <User> findUserByName (String name) throws Exception; // Add the user information public void insertUser (User) throws Exception; // Delete the user information public void deleteUser (int id) throws Exception ;}
3.3 mapper. xml
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapperPUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- 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 = "joanna. yan. mybatis. mapper. userMapper "> <select id =" findUserById "parameterType =" java. lang. integer "resultType =" joanna. yan. mybatis. entity. user "> select * from user where id =#{ id} </select> <select id =" findUserByName "parameterType =" java. lang. string "resultType =" joanna. yan. mybatis. entity. user "> select * from user where username LIKE '% $ {value} %' </select> </mapper>
3.4 load er. xml in SqlMapConfig. xml

3.5 Test
Public class UserMapperTest {private SqlSessionFactory sqlSessionFactory; @ Before public void setUp () throws IOException {// create sqlSessionFactory // mybatis configuration file String resource = "SqlMapConfig. xml "; // get the configuration file stream InputStream inputStream = Resources. getResourceAsStream (resource); // create a session factory and input the configuration file information of mybatis sqlSessionFactory = new SqlSessionFactoryBuilder (). build (inputStream) ;}@ Test public void findUserByIdTest () throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); // create a UserMapper object. mybatis automatically generates the mapper proxy object UserMapper userMapper = sqlSession. getMapper (UserMapper. class); // call the userMapper method User user = userMapper. findUserById (1); System. out. println (user) ;}@ Test public void findUserByNameTest () throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); // create a UserMapper object. mybatis automatically generates the mapper proxy object UserMapper userMapper = sqlSession. getMapper (UserMapper. class); // call the userMapper method List <User> list = userMapper. findUserByName ("James"); System. out. println (list );}}
3.6 summary of some issues 3.6.1 The proxy object internally calls selectOne or selectList

If the mapper method returns a single pojo object (not a collection object), the proxy object internally queries the database through selectOne.

If the er method returns a collection object, the proxy object uses selectList to query the database.

3.6.2 only one method parameter of the mapper interface can affect system development.

There can be only one method parameter for the mapper interface, and the system is not conducive to expansion and maintenance.

In the system framework, the code at the dao layer is shared by the business layer.

Even if the mapper interface has only one parameter, pojo of the packaging type can be used to meet the needs of different business methods.

Note: The parameters of the persistent layer method can use the packaging type, Map, and so on. We recommend that you do not use the packaging type in the service method (not conducive to the scalability of the Business Layer ).

If this article is helpful to you, please let me know ~

Related Article

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.