2021-04-05

MyBatis工程搭建

创建项目
新建Maven项目mybatis-demo
代码:

# 删除mybatis_demo数据库
drop database if exists mybatis_demo;

# 创建mybatis_demo数据库
create database mybatis_demo;

# 使用mybatis_demo数据库
use mybatis_demo;

# 创建account表
create table user (
    id int auto_increment primary key,
    username varchar(20),
    age int,
    score int
);

# 新增数据
insert into user (id, username, age, score) values
(1,'peter', 18, 100), (2,'pedro', 24, 200),
(3,'jerry', 28, 500), (4,'mike', 12, 300),
(5,'tom', 27, 1000);

引入MySQL驱动包

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

JDBCDemo.java

public class JDBCDemo {
    public static void main(String[] args) throws Exception {        //1.注册驱动        Class.forName("com.mysql.cj.jdbc.Driver");        //2.获取连接        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis_demo", "root", "root");        //3.获取Statement对象        PreparedStatement preparedStatement = connection.prepareStatement("select * from user WHERE id = ?");        preparedStatement.setInt(1, 1);        //4.执行SQL语句返回结果集        ResultSet resultSet = preparedStatement.executeQuery();        //5.遍历结果集        while (resultSet.next()) {            System.out.println("username: " + resultSet.getString("username"));            System.out.println("age: " + resultSet.getString("age"));        }        //6.释放资源        resultSet.close();        preparedStatement.close();        connection.close();    }}

引入MyBatis依赖

https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>    <groupId>org.mybatis</groupId>    <artifactId>mybatis</artifactId>    <version>3.5.6</version></dependency><!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic --><dependency>    <groupId>ch.qos.logback</groupId>    <artifactId>logback-classic</artifactId>    <version>1.3.0-alpha5</version>    <scope>test</scope></dependency>

新建StartNoXml.java

@SuppressWarnings({"SqlResolve", "SqlNoDataSourceInspection", "Duplicates"})
public class StartNoXml {
    public static void main(String[] args) throws SQLException {
        // 准备jdbc事务类
        JdbcTransactionFactory jdbcTransactionFactory = new JdbcTransactionFactory();
        // 配置数据源
        PooledDataSource dataSource = new PooledDataSource(
                "com.mysql.cj.jdbc.Driver",
                "jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false",
                "root",
                "root");
        // 配置环境,向环境中指定环境id、事务和数据源
        Environment environment = new Environment.Builder("development")
                .transactionFactory(jdbcTransactionFactory)
                .dataSource(dataSource).build();
        // 新建 MyBatis 配置类
        Configuration configuration = new Configuration(environment);
        // 得到 SqlSessionFactory 核心类
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        // 开始一个 sql 会话
        SqlSession session = sqlSessionFactory.openSession();
        // 得到 sql 连接并运行 sql 语句
        PreparedStatement preStatement = session
                .getConnection()
                .prepareStatement("SELECT * FROM user WHERE id = ?");
        preStatement.setInt(1, 1);
        ResultSet result = preStatement.executeQuery();
        // 验证结果
        while (result.next()) {
            System.out.println("username: " + result.getString("username"));
            System.out.println("age: " + result.getString("age"));
        }
        // 关闭会话
        session.close();
    }
}

在resources文件夹下新建配置文件: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>    <!-- 环境变量 -->    <environments default="development">        <environment id="development">            <!-- 事务管理器 -->            <transactionManager type="JDBC"/>            <!-- 数据源 -->            <dataSource type="POOLED">                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false"/>                <property name="username" value="root"/>                <property name="password" value="root"/>            </dataSource>        </environment>    </environments></configuration>

配置StartWithXml.java


InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值