Write in front:

Hello, everyone! Last time we introduced the Spring MVC primer

This time let us learn the SSM framework in MyBatis entry ~

Mind mapping:


1. Introduction;

  • Mybatis is an excellent Java-based persistence layer framework that encapsulates JDBC internally, allowing developers to focus only on the SQL statements themselves.
  • Mybatis configures various statements to be executed through XML or annotations, and generates the final SQL statement by mapping Java objects to the dynamic parameters of the SQL in the statement. Finally, mybatis framework executes SQL and maps the results to Java objects and returns them. ORM is used to solve the problem of entity and database mapping.

2. introductory configuration.

1. Configure the database. SQL > alter database db_test; create table db_test;


2. Create Maven project and import related dependencies;

<dependencies>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version> 3. 54.</version>
 </dependency>  <dependency>  <groupId>mysql</groupId>  <artifactId>mysql-connector-java</artifactId>  <version> 51.47.</version>  </dependency>  <dependency>  <groupId>log4j</groupId>  <artifactId>log4j</artifactId>  <version> 12.15.</version>  </dependency>  </dependencies>  <build>  <resources>  <resource>  <directory>src/main/java</directory>  <includes>  <include> * */*.xml</include>  </includes>  </resource>  </resources>  </build>s Copy the code

3. We write mapping interfaces. Class concrete implementation methods, are written in the mapping interface; Commonly known as Mapp ERS, also called DAO layer;

public interface UserDao {

    / * ** Query all operations * @return * /  List<User> findAll(a); } Copy the code

4, MyBatis master configuration file sqlmapconfig. XML (resources directory);


      
<! DOCTYPE configurationPUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<! Mybatis master configuration file -->
<configuration>  <! -- Configure the environment -->  <environments default="mysql">  <! Mysql > create mysql  <environment id="mysql">  <! -- Set transaction type -->  <transactionManager type="JDBC"></transactionManager>  <! -- Configure data source (connection pool) -->  <dataSource type="POOLED">  <! -- Configure 4 basic information for connecting to database -->  <property name="driver" value="com.mysql.jdbc.Driver"/>  <property name="url" value="jdbc:mysql://localhost:3306/db_test? useSSL=false"/>  <property name="username" value="root"/>  <property name="password" value="123456"/>  </dataSource>  </environment>  </environments>   <! -- Specify the location of the mapping configuration file, which is a separate configuration file for each DAO.  <mappers>  <mapper resource="com/java/dao/UserMapper.xml"/>  </mappers> </configuration> Copy the code

5. The configuration file usermapper. XML is unique to User (note that it must be the same as the package file of UserDao, preferably together).


      
<! DOCTYPE mapperPUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.java.dao.UserDao">
 <! -->  <select id="findAll" resultType="com.java.model.User">  select * from user  </select> </mapper> Copy the code

3. program files;

1. User entity class; Here we write an entity class that corresponds to the user table in the database. Including entity attributes, get set methods and override toString methods;

    private int id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
  @Override  public String toString(a) {  return "User{" +  "id=" + id +  ", username='" + username + '\' ' +  ", birthday=" + birthday +  ", sex='" + sex + '\' ' +  ", address='" + address + '\' ' +  '} ';  } Copy the code

2. Test Test class. Create a new Test folder in the SRC directory to store the Test classes.


import com.java.dao.UserDao;
import com.java.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;  import java.io.InputStream; import java.util.List;  / * * * @author hk * Introduction to Mybatis case* / public class MyBatisTest {   / * ** Introductory Cases * @param args * /  public static void main(String[] args)throws Exception {  //1. Read the configuration file  InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");  // create SqlSessionFactory  SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();  SqlSessionFactory factory = builder.build(in);  //3. Use the factory to produce SqlSession objects  SqlSession session = factory.openSession();  //4. Use SqlSession to create a proxy object for the Dao interface  UserDao userDao = session.getMapper(UserDao.class);  //5. Use proxy objects to execute methods  List<User> users = userDao.findAll();  for(User user : users){  System.out.println(user);  }  //6. Release resources  session.close();  in.close();  } }  Copy the code

Right click to run the test class, you can see that there is no problem; To this, MyBatis entry program written!


4. Matters needing attention;

  • UserDao and UserMapper. XML:

    The names of these two files, as mentioned above, in the MyBatis persistence layer, call the operation interface and mapping file Mapper;

  • MyBatis: User mapper.xml

    This file must be the same as the DAO layer interface package structure, preferably together; IDEA does not compile SRC Java directory XML files. The solution is to add the following code to the POM configuration file:

    <build>
        <resources>
          <resource>
            <directory>src/main/java</directory>
            <includes>
     <include> * */*.xml</include>  </includes>  </resource>  </resources>  </build> Copy the code
  • The namespace attribute of the label in the mapping configuration file usermapper.xml must be the fully qualified class name of the UserDao interface; In addition, the value of id in its operation configuration (SELECT) must be the method name of the interface;


Well, today is the first to share here, next time to continue to bring you SSM related learning! More dry goods, quality articles, welcome to pay attention to my original technology public number ~


This article is formatted using MDNICE