JPA的乐观锁实现并发执行SQL案例

发布时间:2024年01月11日

JPA乐观锁实现增删改查操作

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Version
    private int version;

    // 构造函数、getter和setter省略
}
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.OptimisticLockException;
import javax.persistence.Persistence;
// dao层
public class ProductDAO {
    private EntityManagerFactory entityManagerFactory;

    public ProductDAO() {
        entityManagerFactory = Persistence.createEntityManagerFactory("your-persistence-unit-name");
    }

    public void createProduct(Product product) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();

        try {
            transaction.begin();
            entityManager.persist(product);
            transaction.commit();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            entityManager.close();
        }
    }

    public Product getProductById(Long id) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        Product product = null;

        try {
            product = entityManager.find(Product.class, id);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            entityManager.close();
        }

        return product;
    }

    public void updateProduct(Product product) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();

        try {
            transaction.begin();
            entityManager.merge(product);
            transaction.commit();
        } catch (OptimisticLockException e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            entityManager.close();
        }
    }

    public void deleteProduct(Product product) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();

        try {
            transaction.begin();
            entityManager.remove(entityManager.merge(product));
            transaction.commit();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            entityManager.close();
        }
    }
}

在上面的代码中,ProductDAO类用于执行对Product实体的增删改查操作。在创建、更新和删除操作中,使用了乐观锁机制来处理并发冲突。

要使用上述代码,需要按照以下步骤进行:

  1. 创建名为"your-persistence-unit-name"的持久化单元,配置与数据库的连接信息。

  2. 创建一个Product对象,并设置相应的属性。

  3. 创建ProductDAO对象,并调用其相应的方法执行数据库操作。

public class Main {
    public static void main(String[] args) {
        ProductDAO dao = new ProductDAO();

        // 创建Product对象并保存到数据库
        Product product = new Product();
        product.setName("Phone");
        dao.createProduct(product);

        // 根据ID查询Product对象
        Product retrievedProduct = dao.getProductById(1L);
        System.out.println("Retrieved Product: " + retrievedProduct.getName());

        // 更新Product对象
        retrievedProduct.setName("New Phone");
        dao.updateProduct(retrievedProduct);

        // 删除Product对象
        dao.deleteProduct(retrievedProduct);
    }
}

以上代码演示了使用乐观锁实现JPA的增删改查操作的完整案例。你可以根据自己的实际需求进行修改和扩展。记得替换代码中的"your-persistence-unit-name"为你实际的持久化单元名称。

JPA的并发执行SQL增删改查的案例

导入依赖

<dependencies>
    <!-- JPA API -->
    <dependency>
        <groupId>jakarta.persistence</groupId>
        <artifactId>jakarta.persistence-api</artifactId>
        <version>2.2.3</version>
    </dependency>

    <!-- JPA Provider (例如Hibernate) -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.1.Final</version>
    </dependency>

    <!-- 数据库驱动 (根据你使用的数据库选择适当的依赖) -->
    <dependency>
        <groupId>数据库驱动的groupId</groupId>
        <artifactId>数据库驱动的artifactId</artifactId>
        <version>数据库驱动的版本号</version>
    </dependency>
</dependencies>

jpa配置省略

假设我们有一个简单的实体类Product,代表产品,包含idnamestock字段:

@Entity
//设置实体类
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private int stock;

    @Version
    private int version;

    // 构造函数、getter和setter省略
}

在这个案例中,我们将实现以下功能:

  1. 创建新产品并保存到数据库。
  2. 根据产品ID查询产品信息。
  3. 更新产品的库存数量。
  4. 删除产品。

下面是完整的代码demo:

import javax.persistence.*;

public class ConcurrentJpaOperations {
    private EntityManagerFactory entityManagerFactory;

    public ConcurrentJpaOperations() {
        entityManagerFactory = Persistence.createEntityManagerFactory("your-persistence-unit-name");
    }

    public void createProduct(Product product) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();

        try {
            transaction.begin();
            entityManager.persist(product);
            transaction.commit();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            entityManager.close();
        }
    }

    public Product getProductById(Long id) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        Product product = null;

        try {
            product = entityManager.find(Product.class, id);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            entityManager.close();
        }

        return product;
    }

    public void updateProductStock(Long id, int newStock) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();

        try {
            transaction.begin();
            Product product = entityManager.find(Product.class, id);

            if (product != null) {
                product.setStock(newStock);
                entityManager.merge(product);
            }

            transaction.commit();
        } catch (OptimisticLockException e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            entityManager.close();
        }
    }

    public void deleteProduct(Long id) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();

        try {
            transaction.begin();
            Product product = entityManager.find(Product.class, id);

            if (product != null) {
                entityManager.remove(product);
            }

            transaction.commit();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            entityManager.close();
        }
    }

    public static void main(String[] args) {
        ConcurrentJpaOperations jpaOperations = new ConcurrentJpaOperations();

        // 创建新产品
        Product product1 = new Product();
        product1.setName("Product 1");
        product1.setStock(10);
        jpaOperations.createProduct(product1);

        // 并发更新产品库存
        Thread thread1 = new Thread(() -> {
            jpaOperations.updateProductStock(1L, 5);
        });

        Thread thread2 = new Thread(() -> {
            jpaOperations.updateProductStock(1L, 3);
        });

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 查询并输出产品信息
        Product retrievedProduct = jpaOperations.getProductById(1L);
        if (retrievedProduct != null) {
            System.out.println("Retrieved Product: " + retrievedProduct.getName());
            System.out.println("Stock: " + retrievedProduct.getStock());
        }

        // 删除产品
        jpaOperations.deleteProduct(1L);
    }
}

在上述代码中,我们创建了一个名为ConcurrentJpaOperations的类,其中包含了创建产品、查询产品、更新产品库存和删除产品的方法。在更新产品库存的方法中,我们使用乐观锁来处理并发冲突。在main方法中,我们创建了两个线程并发地更新产品库存。最后,我们查询并输出产品信息,然后删除产品。

文章来源:https://blog.csdn.net/m0_68856746/article/details/135538052
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。