小编Jav*_*ner的帖子

spring.jpa.properties.hibernate 和 spring.jpa.hibernate 之间的区别

我正在开发一个Spring Boot项目并使用Spring Data JPAwithHibernate作为JPA实现。

目前在我的application.yml文件中我有以下属性:

spring:
    jpa:
        show-sql: true
        properties:
            hibernate:
                format_sql: true
                generate_statistics: true
        hibernate:
            ddl-auto: none
            dialect: org.hibernate.dialect.H2Dialect
Run Code Online (Sandbox Code Playgroud)

Hibernate 属性有不同的前缀(spring.jpa.properties.hibernatespring.jpa.hibernate

具有这些差异的目的是什么?它们可以互换使用,这意味着我可以替换spring.jpa.properties.hibernate.format_sqlspring.jpa.hibernate.format_sql

hibernate spring-data-jpa spring-boot

12
推荐指数
1
解决办法
1万
查看次数

Spring @Transactional 什么时候锁数据库表行

我正在使用 Spring data JPA,并且有一个使用 Spring 的 @Transactional 注释进行注释的方法。在该方法中,我从数据库中获取实体。有些实体用于只读目的,而有些实体则在该事务中更新。让我们举个例子

@Transactional
public void method1(Long id) {
    var entityA = repositoryA.findById(id);
    var entityB = repositoryB.findByOtherId(id);

    entityA.setProperty1(entityB.getProperty() + 1);
}

@Transactional
public void method2(Long id) {
    var entityA = repositoryA.findById(id);
    var entityB = repositoryB.findByOtherId(id);

    entityA.setProperty2(entityB.getProperty() + 2);
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,假设entityA和分别entityB对应于tableA和,并且和是 的两列。另外,我使用的是 SQL Server,因此默认隔离级别是tableBproperty1property2tableAREAD_COMMITTED

我有以下问题:

  1. 执行完该行后,var entityA = repositoryA.findById(id);如何确定应该获取哪种类型的锁?在上面的例子中,我们在更新数据tableA和读取数据tableB,那么这里获取的是不同的锁吗?

  2. 假设两个method1method2都与同一个 同时调用id。首先获取锁的线程会阻塞第二个线程还是两者并行执行?我知道隔离级别是,READ_COMMITTED …

java multithreading hibernate spring-data-jpa

6
推荐指数
1
解决办法
1万
查看次数

了解上下文切换期间的 Java 内存模型

最近在一次会议演讲中,使用以下示例来演示多线程环境中的 Java 内存模型。

public class A {

    public static boolean done;

    public static void main(String[] args) throws InterruptedException {
        done = false;
        new Thread(new Runnable(){
            public void run() {
                System.out.println("running...");

                int count = 0;
                while (!done) {
                    count++;
                }

                System.out.println("Exiting thread");
            }
        }).start();

        System.out.println("in main...");
        Thread.sleep(2000);

        System.out.println("setting done to true");
        done = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道上面代码中创建的新线程永远不会退出,因为done变量被缓存在线程的本地缓存中。一个适当的解决方案是使done变量可变。

但是如果在while循环中,我们调用Thread.sleep()如下

    while (!done) {
        count++;
        try {Thread.sleep(0);} catch(Exception e){}
    }
Run Code Online (Sandbox Code Playgroud)

然后线程成功退出。

我的理解是,由于sleep(0)会发生上下文切换,这将使缓存条目无效,因此每次done检索的更新值。我的理解正确吗?这种行为也取决于机器的核心数吗?

java multithreading java-memory-model

5
推荐指数
1
解决办法
75
查看次数