MyBatis开发环境搭建

1.创建工程

在这里插入图片描述

MyBatis开发环境搭建_第1张图片

MyBatis开发环境搭建_第2张图片

2.引入相关的依赖 pom.xml

    <dependencies>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.6version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.18version>
            <scope>runtimescope>
        dependency>

        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
    dependencies>

3.准备数据库

这里使用的是数据库是mybatis

MyBatis开发环境搭建_第3张图片

use mybatis;
create table users(
    uid int primary key auto_increment,
    uname varchar(20) not null,
    uage int not null
);
insert into users(uid,uname,uage) values(null,'张三',20),(null,'李四',18);

4.创建mybatis的核心配置文件所使用的db.properties文件

MyBatis开发环境搭建_第4张图片

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
jdbc.username=root
jdbc.password=root

5.创建项目结构

5.1 创建com.example.pojo包存放实体类User

MyBatis开发环境搭建_第5张图片
实体类User的内容如下

package com.example.pojo;

/**
 * ClassName: User
 * Package: com.example.pojo
 * Description:
 *
 * @Create 2023/3/16 7:52
 * @Version 1.0
 */
public class User {
    private int uid;
    private String uname;
    private int uage;

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public int getUage() {
        return uage;
    }

    public void setUage(int uage) {
        this.uage = uage;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", uname='" + uname + '\'' +
                ", uage=" + uage +
                '}';
    }
}

5.2 创建com.example.mapper包存mapper接口

MyBatis开发环境搭建_第6张图片
UserMapper接口如下

package com.example.mapper;

/**
 * ClassName: UserMapper
 * Package: com.example.mapper
 * Description:
 *
 * @Create 2023/3/16 7:55
 * @Version 1.0
 */
public interface UserMapper {
}

6.创建Mybatis核心配置文件mybatis-config.xml

mybatis-config.xml内容如下


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <properties resource="db.properties">properties>

    
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>

    
    <typeAliases>
        
        <package name="com.example.pojo"/>
    typeAliases>

    <environments default="development">
        <environment id="development">
            <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>
        
        <package name="com.example.mapper"/>
    mappers>


configuration>

7.创建Mybatis映射文件UserMapper.xml

7.1创建目录结构

MyBatis开发环境搭建_第7张图片
MyBatis开发环境搭建_第8张图片

7.2 UserMapper.xml内容如下


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
    

    

mapper>

8.创建log4j.xml的配置文件

MyBatis开发环境搭建_第9张图片
内容如下:


DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n"/>
        layout>
    appender>
    <logger name="java.sql">
        <level value="debug"/>
    logger>
    <logger name="org.apache.ibatis">
        <level value="info"/>
    logger>
    <root>
        <level value="debug"/>
        <appender-ref ref="STDOUT"/>
    root>
log4j:configuration>

9.创建测试文件TestMybatis.java

MyBatis开发环境搭建_第10张图片
MyBatis开发环境搭建_第11张图片

9.第一个测试案例

根据User的id查找User

9.1 com.example.mapper.UserMapper.java接口文件中添加方法

public interface UserMapper {

    /**
     * 根据用户id查找用户
     */
    public User findUserById(int id);
}

9.2 UserMapper.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.example.mapper.UserMapper">
    <!-- namespace要和mapper接口的全类名保持一致 -->

    <!-- sql语句要和接口的方法名保持一致 -->
    <select id="findUserById"
            parameterType="int"
            resultType="User">
        select * from users where uid = #{id}
    </select>
</mapper>

9.3 com.example.test.TestMybatis.java中添加测试方法

package com.example.test;

import com.example.mapper.UserMapper;
import com.example.pojo.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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * ClassName: TestMyBatis
 * Package: com.example.test
 * Description:
 *
 * @Create 2023/3/16 8:07
 * @Version 1.0
 */
public class TestMyBatis {

    @Test
    public void testFindUserById() throws IOException {
        //1.获取核心配置类
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        //2.创建SqlSessionFacotry
        SqlSessionFactory sqlSessionFacotry = new SqlSessionFactoryBuilder().build(is);
        //3.获取SqLSession对象
        SqlSession session = sqlSessionFacotry.openSession();

        //4.执行sql语句
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.findUserById(1);

        System.out.println("user = " + user);
        //5。释放资源
        session.close();
    }
}

10.运行结果如下

MyBatis开发环境搭建_第12张图片
setting文件


 

 

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  
	<localRepository>D:\repositorylocalRepository>
  
 
  
 
  
  <pluginGroups>
    
  pluginGroups>
 
  
  <proxies>
    
  proxies>
 
  
  <servers>
    
 
    
  servers>
 
  
  <mirrors>
    
	    
        <mirror>
            <id>alimavenid>
            <mirrorOf>centralmirrorOf>
            <name>aliyun mavenname>
            <url>http://maven.aliyun.com/nexus/content/repositories/central/url>
        mirror>
 
        
        <mirror>
            <id>repo1id>
            <mirrorOf>centralmirrorOf>
            <name>Human Readable Name for this Mirror.name>
            <url>http://repo1.maven.org/maven2/url>
        mirror>
 
        
        <mirror>
            <id>repo2id>
            <mirrorOf>centralmirrorOf>
            <name>Human Readable Name for this Mirror.name>
            <url>http://repo2.maven.org/maven2/url>
        mirror>
  mirrors>
 
  
  <profiles>
    
 
    
	<profile>     
      <id>JDK-1.8id>       
      <activation>       
        <activeByDefault>trueactiveByDefault>       
        <jdk>1.8jdk>       
      activation>       
      <properties>       
        <maven.compiler.source>1.8maven.compiler.source>       
        <maven.compiler.target>1.8maven.compiler.target>       
        <maven.compiler.compilerVersion>1.8maven.compiler.compilerVersion>       
      properties>       
    profile>
  profiles>
 
  
settings>

你可能感兴趣的:(mybatis,java,mysql)