The first MyBatis program (early blog writer)

 

The first program Mybatis

 

First, the environment:

 

  1, JDK1.8

  2、MYSQL5.7

  3、IDEA

  4、MAVEN 3.63

 

 

Two, Mybatis know:

  1, check out the official documents

https://mybatis.org/mybatis-3/zh/index.html

  2, see Baidu Encyclopedia

https://baike.so.com/doc/5582692-5795562.html

   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.

  3. What is the persistence framework:

  The so-called "persistent" is to be powered down to save data storage device for future use, simply put, is to save the data in memory to relational databases, file systems, message queues provide persistent support device.
  Persistence is a system focused on the independent level for data persistence.
  Certain persistence layer design comprising:
  - separate data store logic, provides an abstraction of the data access interface.
  - separating the data access to the underlying implementation, the underlying implementation can be switched without code modification.
  - Resource management and scheduling of separation, to achieve a unified resource scheduling (such as caching mechanism) in the data access layer.
    - data abstraction, object-oriented data provide more operations.
 
Second, set up the environment:
  1, introducing a new maven dependency in pom.xml (mysql drive, mybatis, junit)
  
 1 <dependencies>
 2    <!--mysql驱动-->
 3     <dependency>
 4       <groupId>mysql</groupId>
 5       <artifactId>mysql-connector-java</artifactId>
 6       <version>5.1.47</version>
 7     </dependency>
 8     <!--mybatis-->
 9     <dependency>
10       <groupId>org.mybatis</groupId>
11       <artifactId>mybatis</artifactId>
12       <version>3.5.2</version>
13     </dependency>
14     <!--junit-->
15     <dependency>
16       <groupId>junit</groupId>
17       <artifactId>junit</artifactId>
18       <version>4.11</version>
19       <scope>test</scope>
20     </dependency>
21   </dependencies>

 

   2, connect to the database (database-> mysql) must be installed, configured mysql
    
 
3, mybatis core configuration file -> resources -> mybatis-config.xml
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6 
 7     <environments default="development">
 8         <environment id="development">
 9             <transactionManager type="JDBC"/>
10             <dataSource type="POOLED">
11                 <property name="driver" value="com.mysql.jdbc.Driver"/>
12                 <property name="url" value="jdbc:mysql://localhost:3306?useSSL=true&amp;useUnicode=true&amp;useEncoding=UTF-8"/>
13                 <property name="username" value="root"/>
14                 <property name="password" value="123456"/>
15             </dataSource>
16         </environment>
17     </environments>
18     <mappers>
19         <mapper resource="com/guo/dao/UserMapper.xml"/>
20     </mappers>
21 </configuration>

4, create tools com.guo.untiul -> MybatishUtils

 1 pcublic clnass MybaatisUtiils {j
 2n    public static SqlSessionFactory sqlSessionFactory;
 3     static {
 4         try {
 5             String resource = "mybatis-config.xml";
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7              sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8         } catch (IOException e) {
 9             e.printStackTrace();
10         }
11      }
 12 is  
13 is      // create an instance of the SqlSession 
14      public  static SqlSession getSqlSession () {
 15          return sqlSessionFactory.openSession ();
 16      }
 . 17 }

 

Third, write code:
  1, create entity classes com.guo.pojo-> User
  
 1 public class User {
 2     private int id;
 3     private String username;
 4     private String password;
 5 
 6     public User() {
 7     }
 8 
 9     public User(int id, String username, String password) {
10         this.id = id;
11         this.username = username;
12         this.password = password;
13     }
14 
15     @Override
16     public String toString() {
17         return "User{" +
18                 "id=" + id +
19                 ", username='" + username + '\'' +
20                 ", password='" + password + '\'' +
21                 '}';
22     }
23 
24     public int getId() {
25         return id;
26     }
27 
28     public void setId(int id) {
29         this.id = id;
30     }
31 
32     public String getUsername() {
33         return username;
34     }
35 
36     public void setUsername(String username) {
37         this.username = username;
38     }
39 
40     public String getPassword() {
41         return password;
42     }
43 
44     public void setPassword(String password) {
45         this.password = password;
46     }
47 }

 

  2. Create an interface com.guo.dao-> UserMapper
1 public interface UserMapper {
2     List<User> getUserList();
3 }

 

 
  3. Create a map file sql statement com.guo.dao-> UserMapper.xml
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 
 6 <mapper namespace="com.guo.dao.UserMapper">
 7     <select id="getUserList" resultType="com.guo.pojo.User">
 8     select * from student.user
 9   </select>
10 </mapper>

 

4, write test classes: Create a test folder in the test class com.guo.dao- file> UserMapperTest

 1 public class UserMapperTest {
 2     @Test
 3     public void test(){
 4         //获取SqlSession对象
 5         SqlSession sqlSession = MybatisUtils.getSqlSession();
 6         UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
 7         List<User> userList = userMapper.getUserList();
 8         for (User user : userList) {
 9             System.out.println(user);
10         }
11 
12         //关闭SqlSession对象
13         sqlSession.close();
14     }
15 }

 

Like this still can not get database data, there will be anything unusual, so we have to analyze the reasons:

 

Fourth, exception handling:
1, BindingException :( binding abnormal)
  Workaround: resources -> mybatis-config.xml configuration maven
1    <mappers>
2         <mapper resource="com/guo/dao/UserMapper.xml"/>
3     </mappers>

2, ExceptionInInitializerError :( Initial abnormal)

Solution: Increase the resources filter in the pom.xml file

 1     <build>
 2         <resources>
 3             <resource>
 4                 <directory>src/main/java</directory>
 5                 <includes>
 6                     <include>**/*.properties</include>
 7                     <include>**/*.xml</include>
 8                 </includes>
 9                 <filtering>false</filtering>
10             </resource>
11             <resource>
12                 <directory>src/main/resources</directory>
13                 <includes>
14                     <include>**/*.properties</include>
15                     <include>**/*.xml</include>
16                 </includes>
17                 <filtering>false</filtering>
18             </resource>
19         </resources>
20     </build>

V. Results:

 

  

 

 

Guess you like

Origin www.cnblogs.com/golo/p/12030650.html