search
HomeJavajavaTutorialAnalyze how to configure database connection in MyBatis

Analyze how to configure database connection in MyBatis

Feb 19, 2024 pm 03:03 PM
mybatisDatabase ConnectivityConfigurationsql statement

Analyze how to configure database connection in MyBatis

Detailed explanation of the steps for MyBatis to configure database connection requires specific code examples

MyBatis is a popular open source persistence layer framework that is widely used in Java development. When using MyBatis for database operations, you first need to configure the database connection. This article will introduce in detail how to configure MyBatis database connection, and attach specific code examples.

1. Add dependencies

First, add MyBatis dependencies to your project. You can add the following content to the project's pom.xml file:

<dependencies>
    <!-- MyBatis依赖 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <!-- 数据库驱动依赖,根据你使用的数据库类型选择对应的驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>
</dependencies>

Here we take the MySQL database as an example, using MySQL's official driver mysql-connector-java.

2. Create a database

Before configuring MyBatis, you need to create the corresponding database and tables. You can use the MySQL command line or visual tools to create a database, for example:

CREATE DATABASE mybatis_demo;

USE mybatis_demo;

CREATE TABLE user (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    age INT
);

3. Configure MyBatis

Create a file named mybatis-config.xml in the project Configuration file, used to configure database connections. Generally, this file is located in the src/main/resources directory of the project.

<?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" />
                <!-- 数据库连接URL -->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8" />
                <!-- 数据库用户名 -->
                <property name="username" value="root" />
                <!-- 数据库密码 -->
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <!-- 映射器配置,用于定义SQL语句和Java类之间的映射关系 -->
    <mappers>
        <!-- 可以配置多个映射器,这里以Mapper接口为例 -->
        <mapper resource="com/example/mapper/UserMapper.xml" />
    </mappers>
</configuration>

The <environment></environment> tag in the configuration is used to specify the database connection environment. Multiple database connection environments can be configured. The default development environment is used here. In the <datasource></datasource> tag, a data source of type POOLED is used, indicating that the connection pool is used to manage database connections.

4. Create Mapper interface

Create an interface file named UserMapper.java under the com.example.mapper package for Define the mapping relationship between SQL statements and Java classes.

public interface UserMapper {
    // 查询所有用户
    List<User> getAllUsers();
    // 根据ID查询用户
    User getUserById(int id);
    // 插入用户
    void insertUser(User user);
    // 更新用户
    void updateUser(User user);
    // 删除用户
    void deleteUser(int id);
}

Some common database operation methods are defined in this interface, which can be expanded according to actual needs.

5. Create Mapper XML file

Create an XML file named UserMapper.xml under the com.example.mapper package, use Used to write SQL statements and mapping rules.

<?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">
    <!-- 查询所有用户 -->
    <select id="getAllUsers" resultType="com.example.model.User">
        SELECT * FROM user
    </select>
    <!-- 根据ID查询用户 -->
    <select id="getUserById" parameterType="int" resultType="com.example.model.User">
        SELECT * FROM user WHERE id = #{id}
    </select>
    <!-- 插入用户 -->
    <insert id="insertUser" parameterType="com.example.model.User">
        INSERT INTO user (name, age) VALUES (#{name}, #{age})
    </insert>
    <!-- 更新用户 -->
    <update id="updateUser" parameterType="com.example.model.User">
        UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
    </update>
    <!-- 删除用户 -->
    <delete id="deleteUser" parameterType="int">
        DELETE FROM user WHERE id = #{id}
    </delete>
</mapper>

In this XML file, the namespace attribute is used to specify the fully qualified name of the Mapper interface. If the Mapper interface and the XML file are located in different packages, they need to be configured correctly namespace.

6. Use MyBatis for database operations

To use MyBatis for database operations in Java code, you need to first create a SqlSessionFactory object, and then create a ## through the object. #SqlSession object, and use the SqlSession object to perform database operations.

public class App {
    public static void main(String[] args) {
        // 创建MyBatis配置文件的输入流
        InputStream inputStream = App.class.getResourceAsStream("/mybatis-config.xml");
        // 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 创建SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            // 获取UserMapper对象
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            // 调用数据库操作方法
            List<User> users = userMapper.getAllUsers();
            System.out.println(users);
        } finally {
            // 关闭SqlSession
            sqlSession.close();
        }
    }
}

In the above code example, the input stream of the MyBatis configuration file is obtained through the

getResourceAsStream method, and then the SqlSessionFactory object is created. Then, a SqlSession object is created through the openSession method, UserMapper.class is passed in the getMapper method, and a proxy object is returned. , you can call methods defined in the UserMapper interface through this object.

So far, we have introduced in detail the steps to configure the database connection in MyBatis, and attached specific code examples. I hope this article will help you understand and use MyBatis.

The above is the detailed content of Analyze how to configure database connection in MyBatis. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

What are the key components of the Java Runtime Environment (JRE)?What are the key components of the Java Runtime Environment (JRE)?Apr 22, 2025 pm 06:33 PM

JRE is the environment in which Java applications run, and its function is to enable Java programs to run on different operating systems without recompiling. The working principle of JRE includes JVM executing bytecode, class library provides predefined classes and methods, configuration files and resource files to set up the running environment.

Explain how the JVM handles memory management, regardless of the underlying operating system.Explain how the JVM handles memory management, regardless of the underlying operating system.Apr 22, 2025 pm 05:45 PM

JVM ensures efficient Java programs run through automatic memory management and garbage collection. 1) Memory allocation: Allocate memory in the heap for new objects. 2) Reference count: Track object references and detect garbage. 3) Garbage recycling: Use the tag-clear, tag-tidy or copy algorithm to recycle objects that are no longer referenced.

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.