基于Maven构建Mybatis项目

目录

使用的数据库配置参考笔记-example数据库内容

项目根目录添加porm文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.hao.example</groupId>
  <artifactId>MavenMybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <!-- 数据库驱动 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.32</version>
    </dependency>
    <!-- 引入mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <!-- 定义Java版本 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>

    <resources>
      <resource>
        <!-- 由于想将Mapper.xml文件和Mapper接口放在一起,
                                    故将src/main/java添加到资源搜索目录  -->
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <!-- 原有的src/main/resources也要添加到资源搜索目录 -->
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>

</project>

在src/main/resources下创建数据库对应的实体类:Admin,其符合JavaBean的标准

package com.hao.example.po;

public class Admin {
    private Integer id;
    private String username;
    private String password;
    
    public Admin() {

    }
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "Admin [id=" + id + ", username=" + username + ", password="
                + password + "]";
    }
}

在src/main/java下创建AdminMapper接口,用于操作Admin类

AdminMapper和Hibernate中的AdminDao是一个东西,只不过在Mybatis更习惯称为Mapper

package com.hao.example.mapper;

import com.hao.example.po.Admin;

public interface AdminMapper {
    public Admin getAdmin(Integer id);
    public int deleteAdmin(Integer id);
    public int insertAdmin(Admin admin);
}

在src/main/resources下添加数据库配置文件:db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/example?characterEncoding=utf-8
jdbc.username=root
jdbc.password=h66666

在src/main/resources下添加mybatis配置文件:mybatis-config.xml

<?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>
  
  <!-- 引入数据源配置文件  -->
  <properties resource="db.properties" />
  <!-- 为了避免一直编写包全名,定义别名以方便引用Admin类,Admin类可查看代码  -->
  <typeAliases>
    <typeAlias type="com.hao.example.po.Admin" alias="admin"/>
  </typeAliases>

  <!-- 定义数据库环境,且默认使用development环境 -->
  <environments default="development">
    <!-- 定义id为development的数据库环境 -->
    <environment id="development">
      <!-- 采用jdbc事务管理 -->
      <transactionManager type="JDBC"/>
      <!-- 配置数据库连接信息 -->
      <dataSource type="POOLED">
        <property name="driver" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
      </dataSource>
    </environment>
  </environments>
  <!-- 定义映射器 -->
  <mappers>
    <!-- 引入AdminMapper映射器配置文件 -->
    <mapper resource="com/hao/example/mapper/AdminMapper.xml"/>
  </mappers>

</configuration>

在AdminMapper接口的同一目录下创建AdminMapper.xml文件

AdminMapper.xml相当于AdminMapper接口的实现类,Mybatis框架会利用动态代理技术,将AdminMapper.xml文件转化为AdminMapper接口的实现类,因此要注意,AdminMapper接口中的函数,在AdminMapper.xml文件中都要有对应的标签,以执行相应的SQL语句

<?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.hao.example.mapper.AdminMapper">
  <select id="getAdmin" resultType="admin" parameterType="int">
    select * from admin where id = #{id}
  </select>
  <insert id="insertAdmin" parameterType="admin">
    insert into admin(username, password) values(#{username}, #{password})
  </insert>
  <delete id="deleteAdmin" parameterType="int">
    delete from admin where id = #{id}
  </delete>
</mapper>

创建工具类:SqlSessionFactoryUtil类,用于启动Mybatis,获得Mybatis的相关入口

package com.hao.example.utils;

import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 创建SqlSessionFactory的工具类,实现为单例模式
 *
 */
public class SqlSessionFactoryUtil {
    
    // SqlSessionFactory对象
    private static SqlSessionFactory sqlSessionFactory = null;
    // 类线程锁
    private static final Class<SqlSessionFactoryUtil> CLASS_LOCK = SqlSessionFactoryUtil.class;
    
    /**
     * 私有化默认构造函数
     */
    private SqlSessionFactoryUtil() {

    }
    
    /**
     * 构建SqlSessionFactory
     * @return
     */
    public static SqlSessionFactory initSqlSessionFactory(){
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (Exception e) {
            Logger.getLogger(SqlSessionFactoryUtil.class.getName()).log(Level.SEVERE, null, e);
        }
        
        // 为了避免并发状态下的SqlSessionFactory不唯一,需要添加锁
        synchronized(CLASS_LOCK){
            if(sqlSessionFactory == null){
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }
        }
        return sqlSessionFactory;
    }
    
    /**
     * 获得一个新的Session
     * @return
     */
    public static SqlSession openSession(){
        if(sqlSessionFactory == null){
            initSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }
    
}

执行main函数,测试代码,若能成功运行则构建正确

package com.hao.example.main;

import org.apache.ibatis.session.SqlSession;

import com.hao.example.mapper.AdminMapper;
import com.hao.example.po.Admin;
import com.hao.example.utils.SqlSessionFactoryUtil;


public class Main {
    
    public static void main(String[] args) throws Exception {
        
        SqlSession sqlSession = null;
        
        try {
            sqlSession = SqlSessionFactoryUtil.openSession();
            AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
            
            Admin admin = adminMapper.getAdmin(2);
            System.out.println(admin);
            
            sqlSession.commit();
            
        } catch (Exception e) {
            System.out.println(e);
            sqlSession.rollback();
        }finally{
            if(sqlSession != null){
                sqlSession.close();
            }
        }
    }
    
}
    原文作者:MyBatis
    原文地址: https://www.cnblogs.com/tommychok/p/9037006.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞