JDBC Problems in programming

    1. take SQL The statement is hard coded to Java Code , Not conducive to system maintenance .
        Imagine how to solve : take SQL Extracted separately , In profile (xml The way 、properties file ) To configure .
    2. Database connections cannot be reused , It's a waste of database resources .
        Imagine how to solve : Use the database connection pool to manage database connections .
    3. towards Statement When setting parameters , The position of the parameter is hard coded , Not conducive to system maintenance .
        Imagine how to solve : Whether it can automatically transfer Java Object to Statement.
    4. Traversal result set ,resultSet.getString Hard code specifies the column name .
        Imagine how to solve : Can I automatically SQL The query result set is transformed into Java object .

MyBatis Introduce

        MyBatis This is a apache An open source project of iBatis,2010 This project was initiated by apache software foundation Migrate to google code, And renamed it MyBatis.
        MyBatis Is an excellent persistence layer framework , It's right JDBC To encapsulate the process of database operation , Let the developer only need to pay attention SQL In itself , Instead of having to deal with things like registered drivers 、 establish connection、 establish statement、 Manual setting of parameters 、 Result set retrieval, etc JDBC Complex process code .
        MyBatis adopt xml Or primary key will be executed statement Configure it , And pass Java Objects and statement Medium SQL Map to generate the final execution SQL sentence , Finally by MyBatis Framework implementation SQL And map the result to Java Object and return .
        MyBatis It's an incomplete ORM frame ,MyBatis You can also do object relational mapping , But it still needs to be written manually SQL sentence .Hibernate Yes JDBC The package is deep , It's a completely excellent ORM frame , It's fully realized Java Object to Relation Mapping ,SQL No need to write it manually .

Mybatis frame

    Mybatis To configure
    

    1. SqlMapConfig.xml yes MyBatis Core profile for , Configured data source ( Connection pool )、 Business mapper.xml yes MyBatis Map file of .
    2. SqlSessionFactory Conversational factory , User production session SqlSession.
    3. SqlSession conversation , It's a user oriented facade interface , For operating the database (CRUD)
    4. Executor actuator ,SqlSession Through internal Executor Operating the database ,Executor Need to use Mapped Statement To manipulate the database by encapsulating data information in .
    5. Mapped Statement yes MyBatis An underlying encapsulation object , Encapsulates the SQL sentence 、 Pass in SQL Parameters of statement , take SQL The query results are mapped to Java object .

Mybatis Entry procedure

    1. add to jar package Download address : link : http://pan.baidu.com/s/1mgtFYxa  password :vq10 ( Including source code )
        The core jar Bag is :mybatis-3.2.8.jar
        rely on jar Wrapped in lib Under the table of contents
        You also need to add your own database jar package
        Create a Java Project ( The following is the final project diagram )
        
    2. log4j.properties Log files ( Primary user console printing log)
        add to Source Folder :config, And create log4j.properties
        Use the official website configuration directly , Just change it to DEBUG Pattern     
1
2
3
4
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

    3. establish SqlMapConfig.xml The configuration file
        stay config Create under folder SqlMapConfig.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<? xml  version = "1.0"  encoding = "UTF-8"  ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
< configuration >
     <!--  and spring After integration environments Configuration will be abolished  -->
     < environments  default = "development" >
         < environment  id = "development" >
             < transactionManager  type = "JDBC"  />
             < dataSource  type = "POOLED" >
                 < property  name = "driver"  value = "com.mysql.jdbc.Driver"  />
                 < property  name = "url"
                     value = "jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8"  />
                 < property  name = "username"  value = "root"  />
                 < property  name = "password"  value = "root"  />
             </ dataSource >
         </ environment >
     </ environments >
 
</ configuration >

    4. establish po class ,User stay package com.hqu.model Next , And create database and corresponding table to insert test data
        The goal is : take sql The query results are mapped to Java object ,po Class and user Table fields correspond to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package  com.hqu.model;
 
import  java.sql.Date;
 
public  class  User {
     private  int  id;
     private  String username;
     private  String sex;
     private  Date birthday;
     private  String address;
     private  String detail;
     private  float  score;
 
     // getter and setter .. 
}

    5. To write User.xml(mapper.xml file ) stay config Create folder sqlmap And create User.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<? xml  version = "1.0"  encoding = "UTF-8"  ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
< mapper  namespace = "test" >
 
     <!--  Query user information
     select : take select The tag content is called statement
     id: Is in user.xml Unique identification of ,statement Of id
     parmeterType: Point to sql( towards statement in ) The type of the parameter passed in
     #{}: Represents a dot ,{} Medium id Represents the name of the incoming variable , When a single value is passed in {} The variables in can be arbitrary
     resultType: take sql The query result set maps to java Type of object  -->
     < select  id = "findUserByName"  parameterType = "string"  resultType = "com.hqu.model.User" >
         select * from User where username = #{id}
     </ select >
 
     < insert  id = "insertUser"  parameterType = "com.hqu.model.User" >
         insert into
         user(username,birthday,sex,address,detail,score)
         values (#{username},#{birthday},#{sex},#{address},#{detail},#{score})
     </ insert >
</ mapper >

6. take User.xml stay SqlMapConfig.xml To configure

1
2
3
4
5
6
7
< configuration >
     ...
     <!--  Load mapping file  -->
     < mappers >
         < mapper  resource = "sqlmap/User.xml"  />
     </ mappers >
</ configuration >
7. Mybatis Inquiry procedure
    New class test
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public  class  MybatisTest {
 
     SqlSession sqlSession =  null ;
 
     @Before
     public  void  before()  throws  IOException {
     
         String resource =  "SqlMapConfig.xml" // mybatis Configuration file for
 
         InputStream is = Resources.getResourceAsStream(resource);
 
         //  Create a session factory
         SqlSessionFactory sqlSessionFactory =  new  SqlSessionFactoryBuilder().build(is);
 
         sqlSession = sqlSessionFactory.openSession();  //  From in the conversation factory to conversation
     }
 
     @After
     public  void  after() {
         sqlSession.close();  //  Release resources
     }
 
     @Test
     public  void  testSelect() {
         //  adopt sqlSession Operating the database
         //  The first parameter :user.xml Defined statement Of id
         //  The second parameter : Input parameters
         User user = sqlSession.selectOne( "test.findUserByName" "jerome" );
         System.out.println(user);
     }
     
     @Test
     public  void  testInsert() {
 
         User user =  new  User();
         user.setUsername( "jelly" );
         user.setSex( " Woman " );
         user.setAddress( " Shenzhen " );
         user.setScore(12f);
 
         sqlSession.insert( "test.insertUser" , user);
         
         sqlSession.commit();  //  Commit transaction
     }
 
}
end .
code link : http://pan.baidu.com/s/1sjlzpAP  password :exmy

Mybatis Is how to solve JDBC The problem of

    1. take SQL The statement is hard coded to Java Code , Not conducive to system maintenance .
        Imagine how to solve : take SQL Extracted separately , In profile (xml The way 、properties file ) To configure .
        stay mybatis Map file of ( Such as :User.xml) To configure sql sentence .
    2. Database connections cannot be reused , It's a waste of database resources .
        Imagine how to solve : Use the database connection pool to manage database connections .
        stay SqlMapConfig.xml Under the environments Node is configured with connection pool
    3. towards Statement When setting parameters , The position of the parameter is hard coded , Not conducive to system maintenance .( Such as preparedStatement.setString(1,"jerome"))
        Imagine how to solve : Whether it can automatically transfer Java Object to Statement.
          stay User.xml Pass through paramenterType, Type of input parameter , stay sql Statement passing #{} Represents a space occupying symbol ,{} Is written po The property name , Finish automatically will java Object to sql In the sentence .
    4. Traversal result set ,resultSet.getString Hard code specifies the column name .( Such as :resultSet.getString("id"))
        Imagine how to solve : Can I automatically SQL The query result set is transformed into Java object
        User user = sqlSession.selectOne("test.findUserByName", "jerome");

Refer to the podcast open class : link : http://pan.baidu.com/s/1bnbH2qj  password :9f30
Later detailed in-depth video   link :http://pan.baidu.com/s/1qWFTzQ0 password :jqqx ( That's all the information for the time being )
Reference documents :
1. http://mybatis.org/mybatis-3/zh/index.html (MyBatis Official documents )
Corresponding pdf( english ): link :http://pan.baidu.com/s/1pJrL42v password :2yq0
Corresponding pdf( chinese ): link :http://pan.baidu.com/s/1pJqzBDp password :dwhf

MyBatis - Introduce 、 More articles on simple starter programs

  1. JAVAEE——Mybatis The first day : introduction 、jdbc The problem is 、 Architecture introduction 、 Entry procedure 、Dao Development method of 、 Dynamic proxy mode of interface 、SqlMapConfig.xml The document states

    1. Study plan The first day : 1.Mybatis Introduction to 2.Mybatis To get started a)  Use jdbc Problems in operating the database b) Mybatis The architecture of c) Mybatis How to get started with 3.Dao Development method of ...

  2. JAVAEE——SpringMVC The first day : Introduce 、 Entry procedure 、 Architecture explanation 、SpringMVC Integrate MyBatis、 Parameter binding 、SpringMVC and Struts2 The difference between

    1. Study plan   The first day 1.SpringMVC Introduce 2. Entry procedure 3.SpringMVC Architecture explanation a)  Frame structure b)  Component description 4.SpringMVC Integrate MyBatis 5. Parameter binding a) Sp ...

  3. 【mybatis Deep Adventure Series 】mybatis The framework principle of + Entry program analysis

    In the previous post , Xiao Bian introduced springmvc Relevant knowledge points of , In today's blog post , Xiao Bian will introduce mybatis The framework principle of , as well as mybatis How to get started with , Add, delete, modify and query users , What are her strengths and weaknesses and mybatis and ...

  4. springmvc( One ) springmvc Framework principle analysis and simple entry program

    springmvc This framework is really simple , Sensory ratio struts2 It's simpler , Study hard ~ --WH One . What is? springmvc? We know the idea of a three-tier architecture , And if you know ssh Words , You'll understand it more thoroughly ...

  5. SpringMVC Study ( One )———— springmvc Framework principle analysis and simple entry program

    One . What is? springmvc? We know the idea of a three-tier architecture , And if you know ssh Words , You will understand the idea more thoroughly ,struts2 stay web layer ,spring Control in the middle ,hibernate stay dao Layer and database ...

  6. springmvc Framework principle analysis and simple entry program

    One . What is? springmvc? We know the idea of a three-tier architecture , And if you know ssh Words , You will understand the idea more thoroughly ,struts2 stay web layer ,spring Control in the middle ,hibernate stay dao Layer and database ...

  7. mybatis from the shallower to the deeper day01_4 Entry procedure _4.6 According to the user id( Primary key ) Query user information

    4  Entry procedure 4.1  demand According to the user id( Primary key ) Query user information According to the user name fuzzy query user information Add users Delete user Update user 4.2  Environmental Science java Environmental Science :jdk1.7.0_72 eclipse:indi ...

  8. MyBatis(1)- Simple introduction

    brief introduction What is? MyBatis ? MyBatis Is an excellent persistence layer framework , It supports customization SQL. Stored procedures and high-level mappings .MyBatis Almost all of them were avoided JDBC Code and manually set the parameters and get the result set .My ...

  9. Mybatis( One )Mybatis Introduction and introductory procedures

    Mybatis brief introduction : MyBatis Is an excellent persistence layer framework , It's right jdbc To encapsulate the process of database operation , Let the developer only need to pay attention  SQL In itself , Instead of having to deal with things like registered drivers . establish connection. establish ...

Random recommendation

  1. git And install

    One .window install 1. Download path https://git-for-windows.github.io/ 2. How to be in windows Lower installation GIT_ Experience in baidu 3. Finish the first two and open Git bash Can execute g ...

  2. stay logopond Good design Capriccio seen in

    This essay is just my idea about the design work , No joy, no spray. ~ I saw an article about the color matching of Dashen yesterday , Decided to logopond Look at the excellent works in the website , Find inspiration for your own color matching , Learning and learning , Those who have a strong impact on themselves are : With women's high heels ...

  3. kubernetes Source code reading and compiling

    kubernetes Source code reading A good workman does his work well , You must sharpen your tools first . In the reading kubernetes Source code , I've also used several IDE, In the end, it's still in IDEA On . What I'm used to is pycharm(IDEA Of python IDE edition ...

  4. logback 3、 ... and

    One .LoggerFactory.gerLogger() Use : private Logger vitalLogger= LoggerFactory.getLogger("vitalReques ...

  5. English trip EM2-MP4 Teacher:Taylor voiceless consonant Clear consonant &amp; voiced consonant Voiced consonant

    Class content (Lesson) # distinguish  voiceless consonant Clear consonant & voiced consonant Voiced consonant Clear consonant     short   # Brisk Voiced consonant     long ...

  6. Scrutiny of Partner&#39;s individual project Code

    Because teammate's code does not fully realize the complete function of personal project . Implemented features : 1. Count the frequency of a single word 2. Be able to match the effective string according to the format required by the teacher , And output to the specified file . Unrealized : 1. For consecutive words ...

  7. Maven The basic parameters

    -h,--help                              Display help information-am,--also-make                       ...

  8. Jquery Get attribute value

    jq Get the attribute value in a tag :$("#TeamPerformanceYearUl li:eq(0)").attr('data') jq obtain li perhaps td The first property ( Index values start at zero )$( ...

  9. PAT Class A 1038 Recover the Smallest Number

    https://pintia.cn/problem-sets/994805342720868352/problems/994805449625288704 Given a collection of ...

  10. Direct selection sorting (java)

    The logic of direct selection sort is very simple , Array {A1.......An}   First in {A1........An} To get the smallest   And A1 Swap places   And then in {A2..........An} Take out the smallest of   And A2 Swap places . ...