7.4. Transaction Management

A transaction is an atomic sequence of operations that either all succeed or all fail. In Java, Connectiontransactions can be managed through objects. The following example shows how to use transactions for data insertion:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class JdbcTransactionExample {
    public static void main(String[] args) {
        try {
            // 加载数据库驱动并连接到数据库
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "mypassword";
            Connection connection = DriverManager.getConnection(url, username, password);

            // 关闭自动提交,开始事务处理
            connection.setAutoCommit(false);

            // 插入数据
            String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // 添加数据
            preparedStatement.setString(1, "User 4");
            preparedStatement.setInt(2, 35);
            preparedStatement.executeUpdate();

            preparedStatement.setString(1, "User 5");
            preparedStatement.setInt(2, 40);
            preparedStatement.executeUpdate();

            // 提交事务
            connection.commit();

            // 关闭资源
            preparedStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

7. Use an ORM framework

ORM (Object Relational Mapping) frameworks simplify database operations and allow developers to interact with databases in an object-oriented manner. Hibernate and MyBatis are two commonly used Java ORM frameworks. The following is a simple MyBatis example showing how to perform database operations:

First, add MyBatis dependencies:

Maven:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>

Gradle:

implementation 'org.mybatis:mybatis:3.5.6'

Next, create an Userentity class:

public class User {
    private Integer id;
    private String name;
    private Integer age;

    // getter 和 setter
}

Then, create an UserMapperinterface for defining database operation methods:

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper {
    @Select("SELECT * FROM users")
    List<User> findAll();

    @Insert("INSERT INTO users (name, age) VALUES (#{name}, #{age})")
    void insert(User user);
}

Next, create a mybatis-config.xmlconfiguration file to configure MyBatis:

<?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/mydb?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;allowPublicKeyRetrieval=true"/>
                <property name="username" value="root"/>
                <property name="password" value="mypassword"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper class="UserMapper"/>
    </mappers>
</configuration>

Finally, use MyBatis for database operations:

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 java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisExample {
    public static void main(String[] args) {
        try {
            // 加载MyBatis配置文件
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);

            // 创建SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // 打开一个SqlSession
            try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
                // 获取UserMapper接口的实例
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

                // 插入一个用户
                User newUser = new User();
                newUser.setName("User 6");
                newUser.setAge(25);
                userMapper.insert(newUser);

                // 提交事务
                sqlSession.commit();

                // 查询所有用户
                List<User> users = userMapper.findAll();
                for (User user : users) {
                    System.out.println("ID: " + user.getId() + ", Name: " + user.getName() + ", Age: " + user.getAge());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This example shows how to use the MyBatis framework for basic database operations, including inserts and queries. Using the ORM framework can simplify database programming and reduce the workload of developers to directly write SQL statements. Recommended reading:

https://mp.weixin.qq.com/s/dV2JzXfgjDdCmWRmE0glDA

https://mp.weixin.qq.com/s/an83QZOWXHqll3SGPYTL5g

Guess you like

Origin blog.csdn.net/u010671061/article/details/131003223