Mybatis series notes (2) --- mapper proxy method, mybatis --- mapper

Source: Internet
Author: User

Mybatis series notes (2) --- mapper proxy method, mybatis --- mapper

Mapper proxy method

When we write the MVC design, we will write the dao layer and daoimp Implementation Layer. However, if we use the mapper proxy method, we do not need to first implement the daoimp class.

Of course, this requires the following rules:

(1) The Usermapper. java interface must have the same name as Usermapper. xml and must be in the same directory:

(2) The namespace in mapper. xml is equal to the mapper interface address.

(3) The China method of Usermapper. java interface is the same as the statement id in Usermapper. xml.

<! -- 7 comprehensive query --> <select id = "findUserCount" parameterType = "com. study. model. user "resultType =" int "> select count (*) from user where user. sex = # {userCustomer. sex} and user. username like '% $ {userCustomer. username} % '</select>

If you configure these attributes in Usermapper. xml, the interfaces you write must:

1/* The findUserCount interface name must be consistent with the id attribute. 2 * The input parameter must be consistent with parameterType. The preceding parameter is user. Here it is also user3 *. The returned type resultType is int, it must also be int type 4 */5 public int findUserCount (User user User );
(4) Load er. xml in SqlMapConfig. xml
1 <mappers> 2 <! -- Here is what was previously written --> 3 <! -- <Mapper resource = "sqlmap/User. xml"/> --> 4 <! -- To load a single er file through the mapper interface, some rules must be followed: the mapper interface and mapper must be. the xml ing file name must be consistent and in the same directory --> 5 <mapper class = "com. study. mapper. userMapper "/> 6 7 </mappers>

(5) PassMapper proxy method for addition, deletion, modification, and query

A. Compile the user object

Public class User {private int id; private String username; // User name private String sex; // gender private Date birthday; // birthday private String address; // address/** provides the set and get methods and tostring Methods **/}

B.Configure SqlMapConfig. xml

<! DOCTYPE configurationPUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <properties resource =" db. properties "> </properties> <! -- Define an alias --> <typeAliases> <! -- Definition of a single alias: alias, type: ing type --> <! -- <TypeAlias type = "com. study. model. User" alias = "user"/> --> <! -- Batch alias defines the specified package path, automatically scans the pojo under the package, and defines the alias. The default alias is the class name (lowercase or upper case) --> <package name = "com. study. model "/> </typeAliases> <! -- After integration with spring, environments configuration will be abolished --> <environments default = "development"> <environment id = "development"> <! -- Use jdbc Transaction Management --> <transactionManager type = "JDBC"/> <! -- Database connection pool --> <dataSource type = "POOLED"> <property name = "driver" value = "$ {jdbc. driver} "/> <property name =" url "value =" $ {jdbc. url} "/> <property name =" username "value =" $ {jdbc. username} "/> <property name =" password "value =" $ {jdbc. password} "/> </dataSource> </environment> </environments> <! -- Load mapper ing. If the mapper ing is integrated with spring, you can use the mapper scanner provided in the integration package. mappers does not need to be configured here. --> <Mappers> <mapper class = "com. study. mapper. UserMapper"/> </mappers> </configuration>

There are two new knowledge points:

1: <properties resource = "db. properties"> </properties>

Before entering the configuration file for connecting to the database, you can directly write the attribute (Connection database username, password, etc.) in it, but here it is written in the db. properties outside, which better reflects the code flexibility.

2: <typeAliases> label. We configured mapper before. if the parameterType and resultType attributes in the xml file are objects, you must write the full name of the class, and you only need to write the class name through the configuration of the <typeAliases> label.

C. Configure db. properties

jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc\:mysql\://localhost\:3306/studyjdbc.username=rootjdbc.password=root

That's it.

D. Configure UserMapper. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapperPUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- The full name of the UserMapper interface corresponding to the namespace attribute --> <mapper namespace = "com. study. mapper. UserMapper"> <! -- We found that the resultType attribute here does not need to write the full name com. study. model. User of the class, because in --> <! -- The <typeAliases> tag --> <! -- Query user information by id --> <select id = "findUserById" parameterType = "int" resultType = "USER"> SELECT * FROM user WHERE id =#{ id} </select> <! -- Query user information based on user name. Multiple items may be returned --> <select id = "findUserByName" parameterType = "java. lang. string "resultType =" user "> select * from user where username like '% $ {value} %' </select> <! -- Add user --> <insert id = "insertUser" parameterType = "USER"> insert into user (username, birthday, sex, address) VALUES (# {username }, # {birthday}, # {sex}, # {address}) </insert> </mapper>

F. Configure UserMapper. java object

Public interface UserMapper {// query User information based on User id public User findUserById (int id) throws Exception; // query User information public List based on User name <User> findUserByName (String username) throws Exception; // Insert the public void insertUser (User user) throws Exception;
// Delete the User public void deleteUser (int id) throws Exception; // modify the user public void updateUser (User user) throws Exception ;}

E. Write the UserMapperTest class for addition, deletion, modification, and query.

1 import java. io. IOException; 2 import java. io. inputStream; 3 import java. util. arrayList; 4 import java. util. list; 5 6 import org. apache. ibatis. io. resources; 7 import org. apache. ibatis. session. sqlSession; 8 import org. apache. ibatis. session. sqlSessionFactory; 9 import org. apache. ibatis. session. sqlSessionFactoryBuilder; 10 import org. junit. before; 11 import org. junit. test; 12 13 import com. study. mapper. UserMapper; 14 import com. study. model. user; 15 16 17 public class UserMapperTest {18 // session factory 19 private SqlSessionFactory sqlSessionFactory; 20 // create factory 21 @ Before22 public void init () throws IOException {23 String resource = "SqlMapConfig. xml "; 24 InputStream inputStream = Resources. getResourceAsStream (resource); 25 sqlSessionFactory = new SqlSessionFactoryBuilder (). build (inputStream); 26} 27 // search for objects by user ID 28 @ Test29 public void testFindUserById () throws Exception {30 SqlSession sqlSession = sqlSessionFactory. openSession (); 31 // create a proxy object, which is equivalent to 32 UserMapper userMapper = sqlSession. getMapper (UserMapper. class); 33 User user = userMapper. findUserById (1); 34 System. out. println (user); 35} 36 37 // depending on the user's belief, fuzzy query 38 @ Test39 public void testFindUserByUsername () throws Exception {40 SqlSession sqlSession = sqlSes SionFactory. openSession (); 41 UserMapper userMapper = sqlSession. getMapper (UserMapper. class); 42 List <User> list = userMapper. findUserByName ("James"); 43 System. out. println (list); 44} 45 46 // Add User 47 @ Test48 public void testInsertUser () throws Exception {49 SqlSession sqlSession = sqlSessionFactory. openSession (); 50 UserMapper userMapper = sqlSession. getMapper (UserMapper. class); 51 User user = new User (); 52 User. setUsername ("xiao hong"); 53 // here I only add the USER name, other information is not added, the default is null54 // Preparing: INSERT INTO USER (username, birthday, sex, address) VALUES (?,?,?,?) 55 // Parameters: Xiaohong (String), null, null, null56 userMapper. insertUser (user); 57 sqlSession. commit (); 58 sqlSession. close (); 59} 60} 61/* 62 * Delete and modify it. I will not write it here. As you can understand, 63 */

Thank you for your attention. Thank you for your advice!

 

 

 



 

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.