Maven project using mybatis environment to build - all for query functions Maven project to build an environment using mybatis xml-based forms - all based on xml form for query functions

Maven project using mybatis environment to build - all for query functions based on xml form

 

MyBatis is an excellent persistence framework that supports custom SQL, stored procedures and advanced mappings. MyBatis avoids almost all JDBC code and manual setting parameters and obtaining the result set. MyBatis can use simple XML configuration and mapping annotations or native types, interfaces and Java POJO (Plain Old Java Objects, plain old Java object) is recorded in the database.

Examples of how this action will simply query all users to information through a simple analytical use mybatis in Maven project.

1. The present embodiment uses a database to mysql, first create the user table in the database test, and add some basic data.

Copy the code
 1 -- ----------------------------
 2 -- Table structure for user
 3 -- ----------------------------
 4 DROP TABLE IF EXISTS `user`;
 5 CREATE TABLE `user` (
 6   `id` int(11) NOT NULL AUTO_INCREMENT,
 7   `username` varchar(255) NOT NULL,
 8   `password` varchar(255) NOT NULL,
 9   `nick_name` varchar(255) DEFAULT NULL,
10   `sex` int(1) DEFAULT NULL,
11   `register_date` datetime NOT NULL,
12   PRIMARY KEY (`id`)
13 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
14 
15 -- ----------------------------
16 -- Records of user
17 -- ----------------------------
18 INSERT INTO `user` VALUES ('1', '[email protected]', '1ee04e0b1cb5af7367c80c22e42efd8b', '土豆', '1', '2017-06-23 14:24:23');
19 INSERT INTO `user` VALUES ('2', '[email protected]', '1ee04e0b1cb5af7367c80c22e42efd8b', '土豆-2', '1', '2017-06-23 14:24:23');
20 INSERT INTO `user` VALUES ('3', '[email protected]', '1ee04e0b1cb5af7367c80c22e42efd8b', '土豆-3', '1', '2017-06-23 14:24:23');
21 INSERT INTO `user` VALUES ('4', '[email protected]', '1ee04e0b1cb5af7367c80c22e42efd8b', '土豆-4', '1', '2017-06-23 14:24:23');
22 INSERT INTO `user` VALUES ('5', '[email protected]', '1ee04e0b1cb5af7367c80c22e42efd8b', '土豆-5', '1', '2017-06-23 14:24:23');
23 INSERT INTO `user` VALUES ('6', '[email protected]', '1ee04e0b1cb5af7367c80c22e42efd8b', '土豆-6', '1', '2017-06-23 14:24:23');
24 INSERT INTO `user` VALUES ('7', '[email protected]', '1ee04e0b1cb5af7367c80c22e42efd8b', '土豆-7', '1', '2017-06-23 14:24:23');
25 INSERT INTO `user` VALUES ('8', '[email protected]', '1ee04e0b1cb5af7367c80c22e42efd8b', '土豆-8', '1', '2017-06-23 14:24:23');
26 INSERT INTO `user` VALUES ('9', '[email protected]', '1ee04e0b1cb5af7367c80c22e42efd8b', '土豆-9', '1', '2017-06-23 14:24:23');
27 INSERT INTO `user` VALUES ('10', '[email protected]', '1ee04e0b1cb5af7367c80c22e42efd8b', '土豆-10', '1', '2017-06-23 14:24:23');
28 SET FOREIGN_KEY_CHECKS=1;
Copy the code

2. Create the corresponding entity class User class in the project

Copy the code
 1 package com.example.domain;
 2 
 3 import java.io.Serializable;
 4 import java.util.Date;
 5 
 6 public class User implements Serializable{
 7     private Integer id;
 8     private String username;
 9     private String password;
10     private String nickName;
11     private Integer sex;
12     private Date registerDate;
13 
14     public Integer getId() {
15         return id;
16     }
17 
18     public void setId(Integer id) {
19         this.id = id;
20     }
21 
22     public String getUsername() {
23         return username;
24     }
25 
26     public void setUsername(String username) {
27         this.username = username;
28     }
29 
30     public String getPassword() {
31         return password;
32     }
33 
34     public void setPassword(String password) {
35         this.password = password;
36     }
37 
38     public String getNickName() {
39         return nickName;
40     }
41 
42     public void setNickName(String nickName) {
43         this.nickName = nickName;
44     }
45 
46     public Integer getSex() {
47         return sex;
48     }
49 
50     public void setSex(Integer sex) {
51         this.sex = sex;
52     }
53 
54     public Date getRegisterDate() {
55         return registerDate;
56     }
57 
58     public void setRegisterDate(Date registerDate) {
59         this.registerDate = registerDate;
60     }
61 
62     @Override
63     public String toString() {
64         return "User{" +
65                 "id=" + id +
66                 ", username='" + username + '\'' +
67                 ", password='" + password + '\'' +
68                 ", nickName='" + nickName + '\'' +
69                 ", sex=" + sex +
70                 ", registerDate=" + registerDate +
71                 '}';
72     }
73 }
Copy the code
View Code

 3. The following code in dependency pom.xml file, since the present embodiment uses the database it is necessary to add mysql mysql database connected to the drive, and then add mybatis dependent junit test dependent.

Copy the code
 1      <dependency>
 2             <groupId>mysql</groupId>
 3             <artifactId>mysql-connector-java</artifactId>
 4             <version>5.1.6</version>
 5         </dependency>
 6         <dependency>
 7             <groupId>junit</groupId>
 8             <artifactId>junit</artifactId>
 9             <version>4.8</version>
10         </dependency>
11         <dependency>
12             <groupId>org.mybatis</groupId>
13             <artifactId>mybatis</artifactId>
14             <version>3.4.5</version>
15         </dependency>
Copy the code
View Code

4. Create required to build SqlSessionFactory xml, create SqlMapConfig.xml in the resources directory for easy understanding, the explanation of each item are added profile in the configuration file, as follows:

Copy the code
. 1 <XML Version = "1.0" encoding = "UTF-. 8"??> 
 2 <DOCTYPE Configuration! 
 . 3 the PUBLIC "- // 3.0 // EN mybatis.org//DTD Config" 
 . 4 "http://mybatis.org /dtd/mybatis-3-config.dtd "> 
 . 5 <configuration> 
 . 6 <-! all possible configuration of this environment needed in connection environments, each sub-label environment represents an environment, 
 7 although a plurality of environment, but can select only one instance of each SqlSessionFactory environment, must remember to select an environment 
 ambient ID 8 default default (for example: default = "Test") -> 
 . 9 <environments default = "Test" > 
10 <- each element defines the environment environment ID, named mysql just a convenience to identify what kind of connection on behalf of, the actual connection to the database is mysql does not matter! (example: the above mentioned id = "mysql") -> 
11 <environment = ID "MySQL"> 
12 is <!- transaction manager configuration: 
13 type by selecting the type of transaction manager 
14 There are two types of transaction manager with MyBatis:
15 JDBC - this configuration is the direct use of JDBC commit and rollback is provided, which depends on the connection data obtained from the source to manage transactions scope. 
16 MANAGED - This configuration almost did not do anything. It never commit or roll back a connection, but let container to manage the affairs of the entire life cycle (such as context JEE application server) 
17 by default it will close the connection, however, some containers do not want this, so you need to closeConnection property is set to false to prevent its default behavior is closed. For example: 
18 <transactionManager of the type = "the MANAGED"> 
19 <Property name = "closeConnection" value = "false" /> 
20 </ transactionManager> 
21 Tip If you are using Spring + MyBatis, there is no need to configure the transaction manager, because Spring module will use its own manager to cover the previous one. 
22 is -> 
23 is <the transactionManager type = "JDBC"> </ the transactionManager> 
24 <!
26 UNPOOLED- achieve this but each data source to open and close the connection when requested. Although a bit slow, but for simple applications in the database connection is not too high availability requirements, it is a good choice. Different database performance in terms of performance is not the same, for some databases, the use of connection pooling is not important, this configuration is very suitable for this situation. UNPOOLED types of data sources with the following properties. : 
27 Driver - This is the fully qualified class name of the Java JDBC driver (not the data source JDBC driver class may be included). 
28 url - This is the JDBC URL for the database. 
29 username - username to log in to the database. 
30 password - password to log in to the database. 
31 defaultTransactionIsolationLevel - the default connection transaction isolation level. 
DefaultNetworkTimeout 32 - Network of The default timeout value in milliseconds to the wait for See The Database Operation Complete to the API The Documentation of the java.sql.Connection # setNetworkTimeout () for Details.. 
33 is as an option, you can pass properties to the database driver. Just add "driver." In the name prefix attribute. For example:
UTF8 driver.encoding = 34 is 
35 which passes through the encoding attribute value UTF8 DriverManager.getConnection (url, driverProperties) method to a database driver. 
36                  
implemented with a data source 37 POOLED- this concept of "cell" will be organized JDBC connection objects, the authentication initialization and avoids creating a new connection time necessary for instance. This is a popular Web application that concurrent processing request responsive manner. 
38 in addition to the properties mentioned above UNPOOLED, there are more properties to configure the data source POOLED:                 
39 poolMaximumActiveConnections - activities that may be present at any time (i.e. is being used) the number of connections, the default values: 10 
40 poolMaximumIdleConnections - at any time the number of idle connections that may be present. 
41 poolMaximumCheckoutTime - before being forced to return to the pool connection is detected (checked out). The default value: 20,000 milliseconds (i.e. 20 seconds) 
42 is poolTimeToWait - this is a bottom set, if the acquired connection takes quite a long time, connection pool will print a status log and re-try to obtain a connection (to avoid mis-configured in the case has been quiet fail), default: 20000 milliseconds (ie 20 seconds).
43 poolMaximumLocalBadConnectionTolerance - this is a bad connection on the bottom to set tolerance, the role of obtaining a threaded connection from the cache pool for each attempt. If this thread gets to be a bad connection, then the data source allow this thread to try to re-acquire a new connection, but the number of retries should not exceed the sum of poolMaximumIdleConnections with poolMaximumLocalBadConnectionTolerance. Default: 3 (New in 3.4.5) 
44 poolPingQuery - send a query to the database to detect, used to test the connection is working properly and is ready to accept requests. The default is "NO PING QUERY SET", which can lead to with an appropriate error message when the majority of database-driven failure. 
45 poolPingEnabled - whether to enable the ping query. If turned on, you need to set poolPingQuery property as an executable SQL statement (preferably a very fast SQL statements), the default value: false. 
46 poolPingConnectionsNotUsedFor - poolPingQuery the frequency arrangement. And it may be set to the same database connection timeout to avoid unnecessary detection, Default: 0 (i.e., all connections are detected each time - of course only applies when poolPingEnabled is true). 
47                  
48 JNDI - to achieve this is for the data source, such as can be used in such an application server or EJB container, which may be centralized or configuration data in an external source, and then placing a reference JNDI context. This configuration requires only two data sources properties
49 initial_context - This property is used to find the InitialContext context (i.e., initialContext.lookup (initial_context)). This is an optional attribute, if ignored, it will look for data_source properties directly from the InitialContext. 
50 data_source - This is a reference path contextual data source instance position. It will look in the context of their return provided initial_context configuration, then look directly at InitialContext when not provided. 
51 is similar to the configuration and other data sources, properties can be passed directly to the initial context by prefixing "env.". For example: 
52 is env.encoding = UTF8 
53 is that the method will be passed to its constructor UTF8 encoding property value in the initial context (the InitialContext) instantiated. 
54 is -> 
55 <the dataSource type = "the POOLED"> 
56 is <Property name = "Driver" value = "com.mysql.jdbc.Driver" />  
57 is <Property name = "URL" value = "JDBC: MySQL: / / localhost: 3306 / test "/ >
58 <Property name = "username" value = "the root" />
60             </dataSource>
61         </environment>
62         <environment id="test">
63             <!--配置事务-->
64             <transactionManager type="jdbc"></transactionManager>
65             <!--配置连接池-->
66             <dataSource type="POOLED">
67                 <property name="driver" value="com.mysql.jdbc.Driver"/>
68                 <property name="url" value="jdbc:mysql://localhost:3306/test1"/>
69                 <property name="username" value="root"/>
70                 <property name="password" value="123456"/>
71             </dataSource>
72         </environment>
73 is </ Environments> 
74 <-! Path configuration mapping file -> 
75 <by mappers> 
76 <Resource Mapper = "COM / Example / DAO / UserDao.xml" /> 
77 </ by mappers> 
78 </ Configuration>
Copy the code
View Code

 

   XML configuration file contains the settings for MyBatis core system, comprising a database connection instance data source (the DataSource) transactional scope and decisions and transaction manager (the TransactionManager) control method. Notice the XML header, which is used to verify the correctness of XML documents. environment element contains configuration transaction management and connection pools. mappers element contains a set of mapper is (mapper), the mapper XML mapping file contains SQL code and mapping definition information.

  XML SqlSessionFactory constructed from very simple, the configuration file to convert the input stream, using SqSessionlFactoryBuilder SqlSessionFactory constructed by the input stream, was constructed as follows:

1 String resource = "org/mybatis/example/mybatis-config.xml";
2 InputStream inputStream = Resources.getResourceAsStream(resource);
3 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
View Code

5. Create dao layer interface, here UserDao.java

Copy the code
Import com.example.domain.User. 1; 
 2 
 . 3 Import java.util.List; 
 . 4 
 . 5 UserDao {public interface 
 . 6 / * 
 . 7 query for all user information 
 . 8 * / 
 . 9 List <the User> the findAll (); 
10}
Copy the code
View Code

6. resources created in the mapping file, the dao layers create the same directory structure in the directory resources, e.g. com.example.dao, created should be noted that at a level of required resources directory, the directory is created , created under the dao directory and UserDao Mapper interface corresponds to the mapping file UserDao.xml

Copy the code
. 1 <XML Version = "1.0" encoding = "UTF-. 8"??> 
 2 <DOCTYPE Mapper! 
 . 3 the PUBLIC "- // mybatis.org//DTD Mapper 3.0 // EN" 
 . 4 "http://mybatis.org /dtd/mybatis-3-mapper.dtd "> 
 . 5 <-! define a namespace, specify the corresponding mapper dao Interface -> 
 . 6 <mapper namespace =" com.example.dao.UserDao "> 
 . 7 <! - - external resultMap named reference. MyBatis mapping result set is a very powerful feature 
 8 can be used resultMap or resultType, but not both. Due to differences in the database field name in the class named it is necessary to do the mapping result sets -> 
 . 9 <The resultMap ID = "userResultMap" type = "com.example.domain.User"> 
10 <Property Result = "NICKNAME" = column "NICK_NAME" /> 
. 11 <Property Result = "registerDate" column = "register_date"
13 <! - name of the method specified by id attribute dao interface, sql binding to be performed also here, the namespace name + method can be bound to a unique method of encapsulation mapping resultMap specified return results -> 
14 < ID = SELECT "the findAll" The resultMap = "userResultMap"> 
15 SELECT * from User; 
16 </ SELECT> 
. 17 </ Mapper>
Copy the code
View Code

7. Writing test class for testing:

Copy the code
@Test. 1 
 2 the findAll public void () { 
 . 3 the try { 
 .. 1. 4 // read the configuration file to generate input stream of bytes 
 . 5 in the InputStream = Resources.getResourceAsStream ( "the SqlMapConfig.xml"); 
 .. 6 2 // Get SqlSessionFactory 
 Factory new new = a SqlSessionFactory the SqlSessionFactoryBuilder. 7 () Build (in);. 
 .. 8. 3 // Get the SqlSession 
 . 9 SqlSession factory.openSession the session = (); 
.. 4 // 10 acquires the proxy object dao 
11 UserDao mapper = session.getMapper ( UserDao.class); 
.. 5 // 12 is all the way to execute the query 
13 is List <the User> = mapper.findAll List (); 
14 for (the User User: List) { 
15 System.out.println (User);
16             }
17             session.close();
18         }catch (Exception e){
19             e.printStackTrace();
20         }
21 
22     }
Copy the code
View Code

Test Results:

 Reference website: mybatis's Chinese official website http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html

Guess you like

Origin www.cnblogs.com/xichji/p/11410311.html