Construction of Mybatis development environment based on Maven

1. First we need to create a Maven-based java project

2. Create a table in the database and create the corresponding entity class in the idea

 package com.ffyc.mybatisdemo.model;
 ​
 public class Admin {
 ​
      private int id;
      private String account;
      private String password;
      private String xb;
      private String adminPhone;
 ​
 ​
     public String getXb() {
         return xb;
     }
 ​
     public void setXb(String xb) {
         this.xb = xb;
     }
 ​
     public String getAdminPhone() {
         return adminPhone;
     }
 ​
     public void setAdminPhone(String adminPhone) {
         this.adminPhone = adminPhone;
     }
 ​
     public Admin() {
         System.out.println("Admin无参构造");
     }
 ​
     public Admin(String account, String password, String gender) {
         this.account = account;
         this.password = password;
         this.xb = gender;
     }
 ​
     public int getId() {
         return id;
     }
 ​
     public void setId(int id) {
         System.out.println("SetId");
         this.id = id;
     }
 ​
     public String getAccount() {
         return account;
     }
 ​
     public void setAccount(String account) {
         this.account = account;
     }
 ​
     public String getPassword() {
         return password;
     }
 ​
     public void setPassword(String password) {
         this.password = password;
     }
 ​
 ​
 ​
     @Override
     public String toString() {
         return "Admin{" +
                 "id=" + id +
                 ", account='" + account + '\'' +
                 ", password='" + password + '\'' +
                 ", xb='" + xb + '\'' +
                 ", adminPhone='" + adminPhone + '\'' +
                 '}';
     }
 }
 
 
  • Note:

    • We try to ensure that the attribute names are the same as the field names in the database when creating entity classes

    • In the entity class, you must provide public get() and set() methods for private properties

    • Ensure that there is a no-argument constructor in the class

3. Import Mybatis jar package and database driver package in pom.xml

The project coordinates of Mybatis in the Maven warehouse are as follows:

<!--mybatis-->
   <dependency>
     <groupId>org.mybatis</groupId>
     <artifactId>mybatis</artifactId>
     <version>3.4.2</version>
   </dependency>

The project coordinates of the database driver package in the Maven warehouse are as follows:

 <!--mysql-->
 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
 <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>8.0.16</version>
 </dependency>

4. Create an external configuration file to save jdbc connection information

Let's name this file config.properties

 driverName=com.mysql.cj.jdbc.Driver
 url=jdbc:mysql://127.0.0.1:3306/ssmdb?serverTimezone=Asia/Shanghai
 username=root
 password=111
  • Note:

    • Here is the encapsulation of key-value pairs, so there are no double quotes in the configuration property file . Special attention should be paid here

5. Create AdminMapper.xml SQL mapping file

After we create the SQL mapping file, we need to register it in the global configuration file, and then perform SQL mapping in this file.

 <?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE mapper
         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="com.ffyc.mybatisdemo.dao.AdminDao">
     <select id="findAdminById" parameterType="int" resultType="Admin">
         select * from admin where id = #{id}
     </select>
 </mapper>
  • Note:

    • When developing here, we should follow the interface development specification:

      • 1. The namespace namespace here is consistent with the directory where dao is located

      • The id is consistent with the required abstract method name in dao

      • The method name is consistent with the label id in the corresponding mapper

      • The method parameter and return value type are consistent with the parameter return value defined by the label in the mapper

6. Create a global configuration file

The global configuration file is used to configure the connection information of the database. Here we will directly configure the frequently used configuration at one time.

 
<?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE configuration
         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 <configuration>
 <!--  mybatis全局配置文件-->
     <!--读入属性文件-->
     <properties resource="config.properties"></properties>
     <!--全局配置-->
     <settings>
         <!--日志功能-->
         <setting name="logImpl" value="STDOUT_LOGGING"/>
         <!--从经典的数据库命名转为java的驼峰命名-->
         <setting name="mapUnderscoreToCamelCase" value="true"/>
         <!--开启全局二级缓存-->
         <setting name="cacheEnabled" value="true"></setting>
     </settings>
     <!--配置类型别名-->
     <typeAliases>
         <!--<typeAlias type="com.ffyc.mybatisdemo.model.Admin" alias="Admin"></typeAlias>-->
         <package name="com.ffyc.mybatisdemo.model"/>
     </typeAliases>
     <environments default="development">
         <environment id="development">
             <!--事物管理使用配置文件默认的  事物是一次对数据操作过程的管理,必须是满足原子性特能-->
             <transactionManager type="JDBC"/>
             <!--是否使用数据库连接池功能-->
             <dataSource type="POOLED">
                 <property name="driver" value="${driverName}"/>
                 <property name="url" value="${url}"/>
                 <property name="username" value="${username}"/>
                 <property name="password" value="${password}"/>
             </dataSource>
         </environment>
     </environments>
 ​
     <!--注册SQL映射文件-->
     <mappers>
         <mapper resource="mappers/AdminMapper.xml"/>
     </mappers>
 </configuration>
  • Note:

    • Here we need to import our properties file in the <properties> tag to get the database connection

    • The corresponding SQL mapping file must be registered in the <mappers> tag, and each mapper file must be registered in the global configuration file

    • After the log function is enabled, Mybatis will automatically print the log information for us

    • After configuring the type alias for our custom class, we can write the alias directly instead of writing the full class name every time when writing

7. Write dao

We need to create dao as an interface and write the required abstract methods in it

 package com.ffyc.mybatisdemo.dao;
 ​
 import com.ffyc.mybatisdemo.model.Admin;
 import org.apache.ibatis.annotations.Param;
 ​
 public interface AdminDao {
 ​
     Admin findAdminById(int id);
 ​
 }

8. Write test class

 package com.ffyc.mybatisdemo.test;
 ​
 import com.ffyc.mybatisdemo.dao.AdminDao;
 import com.ffyc.mybatisdemo.model.Admin;
 import com.ffyc.mybatisdemo.util.MybatisUtil;
 import org.apache.ibatis.session.SqlSession;;
 import java.io.IOException;
 ​
 public class Test1 {
 ​
     public static void main(String[] args) throws IOException {
 ​
 ​
         //创建SqlSession
         SqlSession sqlSession = MybatisUtil.getSqlSession();
        // Admin admin = sqlSession.selectOne("com.ffyc.admin.findAdminById", 1);
 ​
         //动态生成一个代理对象(mybatis框架生成),由代理对象去调用mapper文件中的方法
         AdminDao adminDao = sqlSession.getMapper(AdminDao.class);
         Admin admin = adminDao.findAdminById(1);
         System.out.println(admin);
         sqlSession.close();
     }
 }
  • Note:

    • Here, since the creation of SqlSessionFactory is relatively expensive and is used to encapsulate the connection information of the database, we do not need to create it once in each test. Therefore, we directly encapsulate the part of creating SQLSessionFactory into a Util class, so that we The entire project only needs to create SQLSessionFactory for the first time, and then directly call the Util method to create SQLSession during subsequent use.

      package com.ffyc.mybatisdemo.util;
       ​
       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.IOException;
       import java.io.InputStream;
       ​
       public class MybatisUtil {
       ​
           static SqlSessionFactory sqlSessionFactory = null;
           static{
               //读取mybatis全局配置文件
               InputStream inputStream = null;
               try {
                   inputStream = Resources.getResourceAsStream("mybatisConfig.xml");
               } catch (IOException e) {
                   e.printStackTrace();
               }
               //创建SqlSessionFactory.由于SQLSessionFactory创建开销大,用于封装数据库连接信息,所以没有必要每次创建
               sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
           }
       ​
           public static SqlSession getSqlSession(){
               return sqlSessionFactory.openSession();
           }
       }

So far, our Maven-based Mybatis framework has been built!!!

Guess you like

Origin blog.csdn.net/weixin_52629592/article/details/125842984