如何使用mybatis查询数据库示例练习01

文章演示了如何创建MySQL数据库和数据表,然后使用IntelliJIDEA构建一个Maven项目,设置多模块结构,并配置MyBatis进行数据库交互。项目包含了MyBatis的核心配置、日志配置、实体类、Mapper接口和XML映射文件,以及测试类用于查询所有国家记录。
摘要由CSDN通过智能技术生成

一、新建数据库及数据表

create database mybatis default CHARACTER set utf8 collate utf8_general_ci;

use mybatis;

create table country(
	id int not null auto_increment,
	countryname varchar(255) null,
	countrycode varchar(255) null,
	primary key(id)
);


insert into country(countryname,countrycode) values ('中国','CN');
insert into country(countryname,countrycode) values ('美国','US');
insert into country(countryname,countrycode) values ('俄罗斯','RU');
insert into country(countryname,countrycode) values ('英国','GB');
insert into country(countryname,countrycode) values ('法国','FR');

二、通过idea新建maven项目

 

将项目中的src目录删除,然后再新建moudle。

 这样可以在一个大工程下,新建很多moudle编写程序,共用pom.xml。导入依赖。

<?xml version="1.0" encoding="UTF-8"?>
<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.shrimpking</groupId>
    <artifactId>mybatistest01</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis-01</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
</project>

 项目结构如下:

 下面把各文件代码贴出来,

mybatis-confing.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核心配置文件-->
<configuration>

    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="mysql123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/shrimpking/entity/CountryMapper.xml"/>
    </mappers>
</configuration>

log4j.properties

#全局配置
log4j.rootLogger=ERROR, stdout

#Mabatis日志配置
log4j.logger.com.shrimpking = TRACE

#控制台输出配置
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

Country.java

package com.shrimpking.entity;

/**
 * @author user1
 */
public class Country
{
    private int id;
    private String countryname;
    private String countrycode;

    public Country()
    {
    }

    public Country(String countryname, String countrycode)
    {
        this.countryname = countryname;
        this.countrycode = countrycode;
    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getCountryname()
    {
        return countryname;
    }

    public void setCountryname(String countryname)
    {
        this.countryname = countryname;
    }

    public String getCountrycode()
    {
        return countrycode;
    }

    public void setCountrycode(String countrycode)
    {
        this.countrycode = countrycode;
    }

    @Override
    public String toString()
    {
        return "Country{" + "id=" + id + ", countryname='" + countryname + '\'' + ", countrycode='" + countrycode + '\'' + '}';
    }
}

CountryMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mpper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.shrimpking.mapper.CountryMapper">
    <select id="selectAll" resultType="com.shrimpking.entity.Country">
        select id,countryname,countrycode from country
    </select>
</mapper>

测试文件

package com.shrimpking.mapper;

import com.shrimpking.entity.Country;
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.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class CountryMapperTest
{

    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init()
    {
        try
        {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Test
    public void test()
    {
        SqlSession session = sqlSessionFactory.openSession();
        try
        {
            List<Country> countryList = session.selectList("selectAll");
            for (Country country : countryList)
            {
                System.out.println(country.toString());
            }
        }
        finally
        {
            session.close();
        }
    }
}

运行文件

得到结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值