Basic steps and code of Mybatis framework

Keywords: Mybatis xml JDBC SQL

Basic steps and code of Mybatis framework

1.ji create the required database
2. Configure the global configuration file mybatis ﹤ config.xml (other file names are preferred)

<?xml version="1.0" encoding="UTF-8"?> 3. Write Java entity class 4. Write the sql mapping file hotelMapper.xml <?xml version="1.0" encoding="UTF-8" ?> select * from hotel where id=#{id} 5. Register the file information of hotel mapper.xml under mybatis ﹣ config.xml, otherwise the file cannot be found. Write the corresponding mapper on 6. Write test class public class TestHotel { @Test public void test() throws IOException { //Create a SqlSessionFactory object based on the configuration file String resource = "mybatis_config.xml"; InputStream is = Resources.getResourceAsStream(resource); //inputStream is a superclass of all classes of byte input stream //getResourceAsStream dynamically gets the location of a file, so that it can get the resources of this file SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); //SqlSessionFactory a compiled memory image of a single database mapping relationship. Instances of its objects can be obtained through the SqlSessionFactoryBuilder object class. //SqlSessionFactoryBuilder() can build an instance of SqlSessionFactory from an XML Configuration file or an instance of a pre customized Configuration. //SqlSessionFactory is also thread safe. Once it is created, it should exist during application execution. Do not create it multiple times during application operation. It is recommended to use the singleton mode. SqlSessionFactory is the factory that creates SqlSession.
    // Add, delete, modify and query the database according to SqlSessionFactory object
    // A SqlSession represents a session with the database, which needs to be opened and closed.
    SqlSession session = sessionFactory.openSession();
    // According to the unique identification of sql (namespace+sql id), notify mybatis which sql statement to execute.
    String statement = "com.pjf.mybatis.mapper.hotelMapper.getHotel";

    // Execute the query and return a hotel object
    // Here, selectOne has two parameters. The first one is the unique identification of sql. It tells mybatis which sql to execute.
    // The latter is the dynamic parameter of sql. Here is the hotel with query id=1001.
    Hotel hotel = session.selectOne(statement, 1001);
    System.out.println(hotel);

    // sqlsession finished closing callback
    session.close();
}

}
7. Write an interface example of hotelMapper: public Hotel getHotel(Integer i);
8. Modify the sql mapping file hotelMapper.xml to define the full class name of the interface, and then modify the sql id to correspond to the methods in the interface, so that the XML and the interface correspond one by one.

<?xml version="1.0" encoding="UTF-8" ?> select id,hotel_name as hotelName, hotel_address as hotelAddress, price from hotel where id=#{id} 9. Modify and write test class public class TestHotel {
public SqlSessionFactory sqlSessionFactory() throws IOException {    //Factory class
    // Profile of mybatis
    String resource = "mybatis_config.xml";
    // Use the class loader to load the configuration file of mybatis (it also loads the associated mapping file) TestHotel.class.getClassLoader() / / get the class loader of the class object         
    InputStream is = Resources.getResourceAsStream(resource);
    // Build the factory of sqlSession
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
    return sessionFactory;             
}

@Test
public void getHotel() throws IOException {
    //If there are multiple sessions, multiple sqlsessionfactories will be created, and the duplicate content will be extracted through the function.
    SqlSessionFactory sessionFactory = sqlSessionFactory();
    // Open jdbc session
    SqlSession session = sessionFactory.openSession();
    // Create an instance of the hotelMapper class
    // Although this is an interface, mybatis will create a new entity class through dynamic proxy
    // You can view the type of this class through System.out.println(hotelMapper.getClass())
    // Output class com.sun.proxy.$Proxy5, and you can see that it is a proxy class.
    HotelMapper hotelMapper = session.getMapper(HotelMapper.class);
    System.out.println(hotelMapper.getClass());

    Hotel hotel = hotelMapper.getHotel(1001);
    System.out.println(hotel);
    session.close();
}

}

10.properties: import the external properties configuration file
Modify in mybatis? Config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 1,mybatis Use properties To bring in the outside properties Content of profile
           resource Introducing resources under classpath 
           url Introduce resources under network path or disk path -->
<properties resource="db.properties"></properties>

<!-- 2,settings Contains many important settings
         setting Identify specific settings 
             name Indicates the name of the setting item 
             value Represents the value of the setting item -->
<settings>
    <setting name="mapUnderscoreToCamelCase" value="true" />
</settings>

<!-- 3,typeAliases by java Alias from type, alias is not case sensitive 
          typeAlias For a specific java Type alias 
               type java The full class name of a class. The default alias is class name lowercase 
               alias Custom alias --> 
<typeAliases>
    <typeAlias type="com.pjf.mybatis.po.Hotel" alias="hotel" />
    <!-- package Batch alias all classes under a package 
       name Indicates that the default alias of the package is class name lowercase
    <package name="com.pjf.mybatis.po" />
    -->
</typeAliases>

<!-- 4,typeHandlers Type processor-->
<typeHandlers>
<typeHandler handler=""/>
</typeHandlers>

<!-- 5,environments Environment configuration, you can configure multiple environments  default Specify an environment for fast switching
           environment To configure a specific environment information, you must have the following two labels. id Represents the unique identity of the current environment
               transactionManager Things Manager
                    type There are two types of things Manager 
                          JDBC
                          managed
               dataSource data source   
                    type    There are three kinds.[UNPOOLED|POOLED|JNDI]
            -->
<environments default="development">
    <environment id="test">
    <transactionManager type="JDBC" />
        <!-- Configure database connection information -->
        <dataSource type="POOLED">
            <property name="driver" value="${jdbc.driver}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.name}" />
            <property name="password" value="${jdbc.password}" />
        </dataSource>
    </environment>
    
    <environment id="development">
        <transactionManager type="JDBC" />
       
<mappers>
    <mapper resource="com/pjf/mybatis/mapper/hotelMapper.xml"></mapper>
11. Add a db.properties file jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring_mybatis jdbc.name=root jdbc.password=tuniu520 12. The previous sql statement can be directly modified to select id,hotel_name as hotelName, hotel_address as hotelAddress, price from hotel where id=#{id}

Modified to

select * from hotel where id=#{id} Mybatis will automatically complete the hump conversion 13.typeHandlers Mapping types in java to types in database
<typeHandlers>
<typeHandler handler="BooleanTypeHandler"/>
</typeHandlers>

Posted by petrosa on Thu, 24 Oct 2019 07:01:50 -0700