Getting started on the first day to resolve Mybatis

 

  1. MyBatis is a Java persistence framework based on internal JDBC made a package, so that developers only need to focus on SQL statements without concern JDBC code, allowing developers to become more simple.
  2. Statement by the various objects MyBatis XML or annotations will be performed to configure the way up, by mapping Java objects and dynamic parameters in the SQL statement, and ultimately execute SQL statements. After executing SQL, the final results have been returned Java objects.
  3. The idea of ​​using ORM.
  4. Create a table in the database. Insert data (using my name mysql database database:. JavaDemo)
  5. . 1  the CREATE TABLE `NBAPlaers` (
     2    ` id` int ( . 11 ) the NOT NULL AUTO_INCREMENT,
     . 3    `username` VARCHAR ( 32 ) the COMMENT the NOT NULL ' username ' ,
     . 4    ` birthday` datetime default NULL the COMMENT ' birthday ' ,
     . 5    `Sex ` char ( . 1 ) default NULL the COMMENT ' sex ' ,
     . 6    ` address` VARCHAR ( 256 ) default NULL the COMMENT ' address',
     7   PRIMARY KEY  (`id`)
     8 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     9 10 insert  into `NBAPlaers`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'Lebron','2018-02-27 17:47:08','','北京'),(2,'Kobe','2018-03-02 15:09:37','','上海'),(3 , ' Irving ' , ' 2018-03-04 11:34:34 ' , ' female ' , ' Shenzhen ' ), ( 4 , ' Davis ' , ' 2018-03-04 12:04:06 ' , ' male ' , ' Guangzhou ' );
  6. Code needs analysis:
    1. Use mybatis query data from the database.
    2. Create a java project, import the required jar package
    3. Write a love Hong Kong and create the same entity class table, the data package
    4. Write mapping configuration file, SQL statements
    5. The preparation of the master configuration file (configuration database-related information). Loading step of mapping file 4, so that when the load of the main configuration file, a mapping configuration file is loaded.
    6. Getting Started API mybatis provided. . . come On
  7. Creating a common Maven project: Figure

    The figure did not need to choose, directly next

  8. GroupId and Artifatid to supplement a name.
  9. After the page is to create a good
  10. We need to coordinate the introduction of the pom.xml file
    <dependencies>
        <!-- mybatis坐标 -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!--mysql驱动包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <!--日志-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    View Code
  11. Creating a NBAPlaers of entity classes, implement the interface Serializable
    . 1  Package zh.test.domain;
     2  
    . 3  Import the java.io.Serializable;
     . 4  Import java.util.Date;
     . 5  
    . 6  / * 
    . 7  prepare a User entity class, and implements Serializable interface object simply represents a class of objects can be It is serialized.
    8  What is the Serializable interface?
    9  an object serialization interface, a class only implements Serializable interface, his objects to be serialized
     10   * / 
    . 11  public  class NBAPlaers the implements Serializable {
     12 is      Private   Integer ID;
     13 is      Private String username;
     14      Private a Date Birthday;
     15      Private String sex;
    16     private String address;
    17 
    18     @Override
    19     public String toString() {
    20         return "NBAPlaers{" +
    21                 "id=" + id +
    22                 ", username='" + username + '\'' +
    23                 ", birthday=" + birthday +
    24                 ", sex='" + sex + '\'' +
    25                 ", address='" + address + '\'' +
    26                 '}';
    27     }
    28 
    29     public Integer getId() {
    30         return id;
    31     }
    32 
    33     public void setId(Integer id) {
    34         this.id = id;
    35     }
    36 
    37     public String getUsername() {
    38         return username;
    39     }
    40 
    41     public void setUsername(String username) {
    42         this.username = username;
    43     }
    44 
    45     public Date getBirthday() {
    46         return birthday;
    47     }
    48 
    49     public void setBirthday(Date birthday) {
    50         this.birthday = birthday;
    51     }
    52 
    53     public String getSex() {
    54         return sex;
    55     }
    56 
    57     public void setSex(String sex) {
    58         this.sex = sex;
    59     }
    60 
    61     public String getAddress() {
    62         return address;
    63     }
    64 
    65     public void setAddress(String address) {
    66         this.address = address;
    67     }
    68 }
    View Code
  12.  UserMapper.xml write a file,

    . 1 <XML Version = "1.0" encoding = "UTF-. 8"??>
     2 <-! Constraint constraint dtd ->
     . 3 ! < DOCTYPE Mapper
     . 4          the PUBLIC "- // 3.0 // mybatis.org//DTD Mapper EN "
     . 5          " http://mybatis.org/dtd/mybatis-3-mapper.dtd ">
     . 6 <-!
     . 7      namespace: mapper interface used to distinguish, generally written mapper full path
     . 8 ->
     9 < namespace = Mapper "zh.test.mapper.UserMapper">
     10      <-!
     . 11          ID attribute: indicates the name of an interface in the method
     12 is          the resultType: a method return type, a fully qualified path (package name + class name)
     13 is      ->
     14      <SELECT ID = "
    findAll" resultType="zh.test.domain.NBAPlaers">
    15          / * 
    16          prepared corresponding sql statement
     . 17           * / 
    18 is           SELECT * from NBAPlaers;
     . 19      </ SELECT>
     20 is </ Mapper>
    View Code
  13. Write a master configuration file, mainly used to configure the connection to the database, the proposed name of the main configuration file is SqlMapConfig.xml
    . 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      <-! plurality environment ->
     . 7      <environments default =" MySQL ">
     . 8          <-! configuration environment ->
     . 9          <environment = the above mentioned id "MySQL">
     10              <-! configuration management things, things that use local policy ->
     11              <transactionManager of the type = "JDBC"> </ transactionManager>
    12              <! - or that it is connected to the pool UNPOOLED the POOLED ->
     13 is             <dataSource type="POOLED">
    14                 <property name="driver" value="com.mysql.jdbc.Driver"/>
    15                 <property name="url" value="jdbc:mysql://127.0.0.1:3306/javaDemo?characterEncoding=utf8"/>
    16                 <property name="username" value="root"/>
    17                 <property name="password" value="root"/>
    18 
    19                 <!--<property name="url" value="jdbc:mysql:///javaDemo"/>-->
    20             </dataSource>
    21         </environment>
    22     </ Environments>
    25<by mappers>
    24     <-! introduction mapping profile ->
    23 is     <mapper resource="mappers/Usermapper.xml"></mapper>
    26 </mappers>
    27 </configuration>
    View Code
  14. The last way to write a unit test results of test queries the database
     1 package zh.test;
     2 
     3 import org.apache.ibatis.annotations.Result;
     4 import org.apache.ibatis.io.Resources;
     5 import org.apache.ibatis.session.SqlSession;
     6 import org.apache.ibatis.session.SqlSessionFactory;
     7 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
     8 import org.apache.log4j.lf5.util.Resource;
     9 import org.junit.Test;
    10 import zh.test.domain.NBAPlaers;
    11 import zh.test.mapper.UserMapper;
    12 
    13 Import java.io.IOException;
     14  Import a java.io.InputStream;
     15  Import java.util.List;
     16  
    . 17  public  class Demo {
     18 is      @Test
     . 19      public  void findUserAll () throws IOException {
     20 is          // load the master configuration file, build SqlSessionFactory object 
    21 is          the InputStream resourceAsStream = Resources.getResourceAsStream ( "sqlMapConfig" );
     22 is          // Create Object sqlSession 
    23 is          SqlSessionFactory Build = new new . the SqlSessionFactoryBuilder () Build (resourceAsStream);
     24         // By factory object, obtaining an object SQLSESSION 
    25          the SqlSession SQLSESSION = build.openSession ();
     26 is          // call sqlsession objects, and traverse 
    27          List <NBAPlaers> = sqlSession.selectList List ( "zh.test.mapper.UserMapper.findAll" );
     28          for (NBAPlaers User: List)
     29          {
     30              System.out.println (User);
     31 is          }
     32          sqlSession.close ();
     33 is          resourceAsStream.close ();
     34 is      }
     35  
    36      @Test
     37 [      public   void findUserAll2 () throws{IOException
     38 is          // load the master configuration file 
    39          the InputStream resourceAsStream = Resources.getResourceAsStream ( "sqlMapConfig" );
     40          a SqlSessionFactory Build = new new the SqlSessionFactoryBuilder () Build (resourceAsStream);.
     41 is          the SqlSession SQLSESSION = build.openSession ();
     42 is          // Get the proxy object, mybatis frame to generate a proxy object 
    43 is          UserMapper Mapper = sqlSession.getMapper (UserMapper. class );
     44 is          // Mapper proxy object point is 
    45          List <NBAPlaers> allPlayers = mapper.findAll ();
     46 is          for(NBAPlaers user:allPlayers)
    47         {
    48             System.out.println(user);
    49         }
    50         sqlSession.close();
    51         resourceAsStream.close();
    52     }
    53 }
    View Code

    Result: The output on the console

 

Guess you like

Origin www.cnblogs.com/LBJLAKERS/p/11324234.html