SSM Framework Learning-Mybatis01

Keywords: Programming JDBC Database Mybatis xml

1. introduction:

Framework: A reusable design of a whole or part of a system, represented by a set of abstract components and methods of interaction between component instances; another definition holds that a framework is an application skeleton customized by application developers. The former is defined in terms of application while the latter is defined in terms of purpose. It is a semi-finished product, and a framework is designed and implemented as part of an application in a given problem domain.

 

MyBatis is an excellent persistence framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manual setting of parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native information, mapping interfaces and Java POJOs(Plain Old Java Objects, ordinary Java objects) into records in the database.

2. guide pack

 

3. Create a new global configuration file under src (write four JDBC variables)

Introducing DTD or schema into the global configuration file

Window->preferences->XML->XMLcatlog

 

xml file configuration jdbc

<!DOCTYPE configuration

  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

  "http://mybatis.org/dtd/mybatis-3-config.dtd">

  <configuration>

  <!-- default Referencing the current environment id -->

  <environments default="default">

     <environment id="default">

     <!-- Use things to configure jdbc Four variables -->

     <transactionManager type="JDBC"></transactionManager>

     <dataSource type="POOLED">

     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

     <property name="url" value="jdbc:mysql://localhost:3306/likui"/>

     <property name="username" value="root"/>

     <property name="password" value="123456"/>

     </dataSource>

     </environment>

  </environments>

  </configuration>

 

4. New package ending with mapper: entity class name + mapper.xml

Write SQL commands that need to be executed, equivalent to implementation classes

<!DOCTYPE mapper

  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  <mapper namespace="com.likui.mapper">

<! -- id: Method name

parameterType: Define parameter types

If the method returns with a list, write the type of list in the resultType because mybatis

For jdbc encapsulation, read data line by line - >

  <select id="selAll" resultType="com.likui.pojo.Flower">

  select * from flower

  </select>

  </mapper>

 

5. Test results (only when mybatis is used alone, and finally not in ssm)

mybatis can automatically map field value names and class entity names in database tables into a consistent form

package com.likui.pojo;

public class Test {

     public static void main(String[] args) throws IOException {

           InputStream is = Resources.getResourceAsStream("mybatis.xml");

           //Use Factory Design Patterns

           SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

           //Production of SqlSession

           SqlSession session=factory.openSession();

           List<Flower> list = session.selectList("a.b.selAll");

           System.out.println("id\t\tname\t\tprice\t\tproduction");

           for (Flower flower : list) {

                         System.out.println(flower.getId()+"\t\t"+flower.getName()+"\t\t"+

           flower.getPrice()+"\t\t"+flower.getProduction());

           }

           session.close();

     }

}

6. Implementing the JDBC tomcat Pool step

UNPOOLED - The implementation of this data source is to open and close the connection each time it is requested. It's a bit slow, but it's a good choice for simple applications that don't require too much database connection availability. Different databases perform differently in terms of performance. For some databases, using connection pools is not important. This configuration is suitable for this situation. Data sources of UNPOOLED type only need to configure the following five attributes:

  • Driver - This is the fully qualified name of the Java class driven by JDBC (not the data source class that may be included in the JDBC driver).
  • url - This is the JDBC URL address of the database.
  • username - username to log in to the database.
  • Password - The password to log in to the database.
  • DefaultTransaction Isolation Level - Default connection transaction isolation level.
  • As an option, you can also pass properties to the database driver. To do this, the prefix of the attribute is "driver." For example:
  • driver.encoding=UTF8
  • This will pass the encoding attribute with UTF8 value to the database driver through the DriverManager.getConnection(url,driverProperties) method.

POOLED - The implementation of this data source uses the concept of "pool" to organize JDBC connection objects, avoiding the necessary initialization and authentication time when creating new connection instances. This is a popular way for concurrent Web applications to respond quickly to requests.

JNDI - This data source is implemented to be used in containers such as EJB or application server, which can centralize or configure data sources externally, and then place a reference to the JNDI context. This data source configuration requires only two attributes:

  • Initial_context - This property is used to find context in Initial Context (that is, initial_context). This is an optional attribute, and if ignored, the data_source attribute will be found directly from the Initial Context.
  • data_source - This is the path to refer to the context of the location of the data source instance. When the initial_context configuration is provided, it will be looked up in the context it returns, and when it is not provided, it will be looked up directly in the Initial Context.

7. Global Profile

<transactionManager/>

type attribute optional value:

  • JDBC - This configuration uses JDBC's commit and rollback settings directly and relies on connections from data sources to manage transaction scopes.
  • MANAGED - This configuration does little. It never commits or rolls back a connection, but lets the container manage the entire lifecycle of the transaction (such as the context of the JEE application server). By default it closes the connection, but some containers don't want to, so you need to set the closeConnection property to false to prevent its default closing behavior.

Data Source

The dataSource element uses the standard JDBC data source interface to configure the resources of JDBC connection objects.

Many MyBatis applications configure data sources according to the examples in the example. Although this is optional, data sources must be configured in order to use lazy loading.

There are three built-in data source types (that is, type="[UNPOOLED|POOLED|JNDI]"):

 

8. Use database connection pool: Open up a space in memory to store multiple database connection objects. JDBC Tomcat Pool, which directly generates database connection pool by tomacat, has active and idle state. The purpose of using database connection pool is to reduce the pressure of server system and improve the efficiency of program operation when accessing database at high frequency.

Conditions: There are database driver files under lib, context.xml files under META-INF, and serverlet files under src.

(1) Information about setting up data connections in context.xml

<Context>

<Resource driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/likui"

username="root" password="123456" maxActive="50" maxIdle="20" name="test"

auth="Container" maxWait="10000"  type="javax.sql.DataSource"/>

</Context>

 

(2) Create a new server net file under src to obtain database connection information and execute it.

@WebServlet("/pool")

public class Demoserverlet extends HttpServlet {

     @Override

     protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

           try {

                Context cxt = new InitialContext();

                DataSource ds = (DataSource) cxt.lookup("java:comp/env/test");  //test is the name of the connection

                Connection conn = ds.getConnection();

                PreparedStatement ps = conn.prepareStatement("select * from flower");

                ResultSet rs = ps.executeQuery();

                res.setContentType("text/html;charset=utf-8");

                PrintWriter out = res.getWriter();

                while(rs.next()){

                     out.print(rs.getInt(1)+"&nbsp;&nbsp;&nbsp;&nbsp;"+rs.getString(2)+"<br/>");

                }

                out.flush();

                out.close();

                rs.close();

           } catch (NamingException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

           } catch (SQLException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

           }

     }

}

The effect diagram is as follows:

9. Three ways of querying

(1)selectList(): The return value is a list type, which is suitable for traversing all the results of the query.

In the xmll configuration file:

<select id="selAll" resultType="com.likui.pojo.Flower">

  select * from flower

  </select>

In the java file:

List<Flower> list = session.selectList("a.b.selAll");

          System.out.println("id\t\tname\t\tprice\t\tproduction");

           for (Flower flower : list) {

                System.out.println(flower.getId()+"\t\t"+flower.getName()+"\t\t"+

           flower.getPrice()+"\t\t"+flower.getProduction());

           }

(2)selectOne():: The return value is an object object object, which is applicable when the return result is only a variable or a row of data.

In the xml configuration file:

  <select id="selById" resultType="int">

   select count(*) from flower where id=1

  </select>

In the java file:

int count=session.selectOne("a.b.selById");

System.out.println(count);

(3)selectMap(): When returning a value, Map is suitable for the requirement to obtain the corresponding value through a column value in the query result.

In the xml configuration file:

 <select id="c" resultType="com.likui.pojo.Flower">

  select * from flower

  </select>

In Java files:

Map<Object,Object> map=session.selectMap("a.b.c", "name");

System.out.println(map);

 

 

Posted by hyp0r on Sat, 11 May 2019 05:15:23 -0700