Mybatis learning notes (3) Dao development, mybatis learning notes

Source: Internet
Author: User

Mybatis learning notes (3) Dao development, mybatis learning notes

When using Mybatis to develop Dao, there are usually two methods: the original Dao development method and the Mapper interface development method, which are commonly used for Mapper interface development.

SqlSession Scope of use
Public class test1 {private static SqlSessionFactory sqlSessionFactory; private static Reader reader; // create a session factory and pass in the configuration file information of mybatis static {try {// get the configuration file stream reader = Resources. getResourceAsReader ("Configuration. xml "); // create a session factory and input the configuration file information of mybatis sqlSessionFactory = new SqlSessionFactoryBuilder (). build (reader);} catch (Exception e) {e. printStackTrace () ;}/// query data public void select () {// obtain sqlsession SqlSession session = sqlSessionFactory through the factory. openSession (); try {// use SqlSession to operate the database // The first parameter: id of the statement in the ing file // The second parameter: specify the parameter parameterType that matches the ing file. User user = (User) session. selectOne ("com. yihaomen. mybatis. model. user. selectUserByID ", 1) ;}finally {session. close ();}}}

To operate databases through mabatis, in addition to various configurations, a specific object needs to be created during testing. For example:

1. SqlSessionFactoryBuilder

SqlSessionFactoryBuilder is used to create SqlSessionFacoty. Once SqlSessionFacoty is created, SqlSessionFactoryBuilder is not required. Because SqlSession is produced through SqlSessionFactory, you can use SqlSessionFactoryBuilder as a tool class, the best scope is the method scope, that is, the local variables in the method body.

2. SqlSessionFactory

SqlSessionFactory is an interface that defines different overload methods of openSession. The best use range of SqlSessionFactory is that it can be used repeatedly once created during the application running. It is usually used to manage SqlSessionFactory in singleton mode.

3. SqlSession

SqlSession is a user-oriented interface that defines database operations. The DefaultSqlSession implementation class is used by default.

SqlSession encapsulates database operations, such as query, insert, update, and delete. SqlSessionFactory is used to create SqlSession, while SqlSessionFactory is created through SqlSessionFactoryBuilder.

Conclusion:

Each thread should have its own SqlSession instance. SqlSession instances cannot be shared. It is also thread-insecure. Therefore, the optimal range is the request or method range. Never put reference of a SqlSession instance in a static field or instance field of a class.

Open a SqlSession. Close it after use. This close operation is usually placed in the finally block to ensure that the close operation can be executed every time.

// Obtain sqlsession SqlSession session = sqlSessionFactory. openSession () through the factory; try {} finally {session. close ();}
Original Dao Development Method

Programmers need to write DAO and DAO implementation classes. Injection to DAO implementation classSqlSessionFactoryIn the method body, SqlSessionFactory is used to create SqlSession.

1. Define the Dao Interface

Public interface UserDAO {// query User findUserById (int id) throws Exception based on the current id; // Add User void insertUser (user User) throws Exception; // Delete the user void deleteUser (int id) throws Exception based on the id ;}

2. Dao implementation class

DAO implementation class/*** @ ClassName: UserDAOImpl * @ Description: DAO implementation class (Note: SqlSession is non-thread-safe, so it cannot be declared as global) */public class UserDAOImpl implements UserDAO {SqlSessionFactory sqlSessionFactory;/*** inject SqlSessionFactory into DAO implementation class (injection through constructor) */public UserDAOImpl (SqlSessionFactory sqlSessionFactory) {this. sqlSessionFactory = sqlSessionFactory;} @ Override public User findUserById (int id) throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); User user = sqlSession. selectOne ("test. findUserById ", id); sqlSession. close (); return user ;}@ Override public void insertUser (User user) throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); sqlSession. insert ("test. insertUser ", user); sqlSession. commit (); sqlSession. close () ;}@ Override public void deleteUser (int id) throws Exception {SqlSession sqlSession = sqlSessionFactory. openSession (); sqlSession. delete ("test. deleteUser ", id); sqlSession. commit (); sqlSession. close ();}}

3. Create a New Source Code directory named test.UserDAOImplClass, right-click to create a Junit Test Case, change the source code directory to test, and select the method we need to Test:

Public class UserDAOImplTest {private SqlSessionFactory sqlSessionFactory;/*** this method is executed Before the test is executed. Obtain a SqlSessionFactory */@ Before public void setUp () throws Exception {sqlSessionFactory = new SqlSessionFactoryBuilder (). build (Resources. getResourceAsStream ("SqlMapConfig. xml ") ;}@ Test public void testFindUserById () throws Exception {// create UserDAO (inject SqlSessionFactory in the construction) UserDAO userDAO = new UserDAOImpl (sqlSessionFactory ); user user = userDAO. findUserById (1); System. out. println (user) ;}@ Test public void testInsertUser () throws Exception {UserDAO userDAO = new UserDAOImpl (sqlSessionFactory); User user = new User (); user. setSex ("2"); user. setUsername ("Sun Wukong"); user. setAddress ("fang inch Ling Taishan"); user. setBirthday (new Date (); userDAO. insertUser (user) ;}@ Test public void testDeleteUser () throws Exception {UserDAO userDAO = new UserDAOImpl (sqlSessionFactory); userDAO. deleteUser (27 );}}
Problems in original DAO Development
  • There are a lot of template methods in the DAO interface implementation class. Imagine: repeated code can be extracted.

  • During the SqlSession method, the Statement id is hardcoded in your DAO implementation class.

  • The input parameters for calling sqlSession-related methods are generic. Even if an incorrect parameter is input, no error is reported during the compilation phase, which is not conducive to programmer development.

Mapper dynamic proxy Mode Implementation Principle

The Mapper interface development method only requires the programmer to write the Mapper interface (equivalent to the Dao Interface), and The Mybatis framework creates the dynamic proxy object of the interface according to the interface definition, the method of the proxy object is similar to the same method of the Dao interface.

Mapper interface development must follow the following specifications: Mapper can automatically generate ER interface implementation class proxy objects.

1. The namespace in the Mapper. xml file is the same as the class path of the mapper interface.

2. The Mapper interface method name is the same as the id of each statement defined in Mapper. xml.

3. The input parameter type of the Mapper interface method is the same as the parameterType type of each SQL statement defined in mapper. xml.

4. The output parameter type of the Mapper interface method is the same as the resultType of each SQL statement defined in mapper. xml.

1. UserMapper. xml configuration file
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- Namespace is used to classify and manage SQL statements. Note: namespace plays a special role in mapper proxy Development --> <mapper namespace = "com. yihaomen. mybatis. dao. IUserOperation "> <! -- Configure many SQL statements in the ing file --> <! -- Id identifies the SQL ing file's SQL, called the statement id. It encapsulates the SQL statement into the mappedStatement object. Therefore, the id is called statement's idparameterType: Specifies the input type resultType: specifies the java object mapped to the SQL output result, select specifies resultType to map a single-pick record to a java object --> <select id = "selectUserByID" parameterType = "int" resultType = "User"> select * from 'user' where id = # {id} </select> <insert id = "addUser" parameterType = "User" useGeneratedKeys = "true" keyProperty = "id"> insert into user (userName, userAg E, userAddress) values (# {userName}, # {userAge}, # {userAddress }) </insert> <update id = "updateUser" parameterType = "User"> update user set userName =#{ userName}, userAge =#{ userAge }, userAddress = # {userAddress} where id = # {id} </update> <delete id = "deleteUser" parameterType = "int"> delete from user where id = # {id} </delete> <select id = "list" resultType = "User"> select * from 'user' </select> <! -- $ {} Indicates concatenating an SQL string, which is the java object type mapped to the single-pick record. Using $ {} For concatenation can easily cause SQL injection $ {value }: concatenates the content of input parameters. If the input type is simple, you can only use value --> <select id = "findUserByName" parameterType = "String" resultType = "User"> select * from 'user' where username like '% $ {value} % '</select> </mapper>
2. UserMapper. java class
Package com. yihaomen. mybatis. dao; import java. util. list; import com. yihaomen. mybatis. model. article; import com. yihaomen. mybatis. model. user; // note: the interface name must be the same as the namespace name in xml. 2. Each name of the interface implementation method corresponds to the id in xml. public interface IUserOperation {// query the data public User selectUserByID (int id ); // Add public void addUser (User user); // update public void updateUser (User user); // Delete public void deleteUser (int id ); // joint query public List <Article> getUserArticles (int id); // list to obtain public List <User> list (); // fuzzy query public List <User> findUserByName (String name );}

After completing the preceding two steps, do not forget to load UserMapper. xml in the sqling file SqlMapConfig. xml!

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

3. Test the UserMapper Interface

Package com. yihaomen. mybatis. ui; import java. io. reader; 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 com. yihaomen. mybatis. dao. IUserOperation; import com. yihaomen. mybatis. model. user; public class Test {private static SqlSessionFac Tory sqlSessionFactory; private static Reader reader; // create a session factory and input the mybatis configuration file information static {try {// get the configuration file stream reader = Resources. getResourceAsReader ("Configuration. xml "); // create a session factory and input the configuration file information of mybatis sqlSessionFactory = new SqlSessionFactoryBuilder (). build (reader);} catch (Exception e) {e. printStackTrace () ;}}// public method, return the initialized sqlSessionFactory object public static SqlSessionFactory getSession () {return sqlSessionFa Ctory;} // query the public void select () {// obtain sqlsession SqlSession session = sqlSessionFactory through the factory. openSession (); try {// use SqlSession to operate the database // The first parameter: id of the statement in the ing file // The second parameter: specify the parameter parameterType that matches the ing file. User user = (User) session. selectOne ("com. yihaomen. mybatis. model. user. selectUserByID ", 1); System. out. println (user. getUserAddress (); System. out. println (user. getUserName ();} finally {session. close () ;}}// Add public void addUser (String address, String name) {// create user Object User user = new User (); user. setUserAddress (address); user. setUserName (name); user. setUserAge (80); // obtain SqlSession session = sqlSessionFactory through the factory. openSession (); try {IUserOperation userOperation = session. getMapper (IUserOperation. class); // Add userOperation data. addUser (user); // submit the session. commit (); // System. out. println ("The added user id is:" + user. getId ();} finally {session. close () ;}// update the public void updateUser (int id, String address) {// obtain the user, modify it, and submit it. SqlSession session = sqlSessionFactory. openSession (); try {IUserOperation userOperation = session. getMapper (IUserOperation. class); User user = userOperation. selectUserByID (id); user. setUserAddress (address); userOperation. updateUser (user); session. commit (); System. out. println ("Update successful !! ");} Finally {session. close () ;}// Delete the public void deleteUser (int id) {SqlSession session = sqlSessionFactory. openSession (); try {IUserOperation userOperation = session. getMapper (IUserOperation. class); userOperation. deleteUser (id); session. commit (); System. out. println ("delete data: id =" + id);} finally {session. close () ;}// list to obtain public void getList () {SqlSession session = sqlSessionFactory. openSession (); try {IUserOperation userOperation = session. getMapper (IUserOperation. class); List <User> us = userOperation. list (); session. commit (); // System. out. println ("generate list:" + us. size ();} finally {session. close () ;}// fuzzy query public void geFindUserByName (String name) {SqlSession session = sqlSessionFactory. openSession (); try {IUserOperation userOperation = session. getMapper (IUserOperation. class); List <User> us = userOperation. findUserByName (name); System. out. println (us. size (); session. commit ();} finally {session. close () ;}} public static void main (String [] args) {Test test = new Test (); // test. getList (); test. geFindUserByName ("small"); // test. addUser ("Hangzhou", "Xiaojiang ");}}
  • What we have doubts is that the ResultType of the user in UserMapper. xml is a common POJO, but the returned value in our own Mapper interface is the List type. Does this cause type inconsistency? However, the proxy object actually callsselectOne()OrselectList()The proxy object automatically determines whether it is a proper method for selecting a separate POJO.

  • Will system maintenance be affected if there is only one method parameter in the Mapper interface? The code at the DAO layer is shared by the business layer. Even if there is only one Mapper interface parameter, we can use the packaged POJO to meet the system requirements.

  • Note: The packaging type can be used in the parameters of methods in the persistent layer, but the packaging type is not recommended in the Service layer (not conducive to the extended maintenance of the Business Layer ).

 

  

 

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.