동일한 트랜잭션 (TestService 서비스 구현의 savePerson() 메소드 내부)에서 두 개의 레코드 (Person)를 삽입하려고합니다.롤백시 스프링 트랜잭션이 DB를 이전 상태로 복원하지 않습니다.
또한 PERSON 테이블의 first_name 열에 고유 한 키 인덱스를 만들었습니다. 따라서 같은 이름의 두 인물을 삽입하려고하면 중복 키 오류가 발생하고 트랜잭션 롤백을 테스트 할 수 있습니다.
savePerson() 메서드를 실행할 때 JTA는 중복 된 키로 인해 롤백을 시작하지만 DB에서도 롤백을 시작하지 않습니다. 여기서 내가 무엇을 놓치고 있니?
MySQL 일반 로그에는 sql "START TRANSACTION"다음에 "ROLLBACK"/ "COMMIT"이 없습니다. 그리고 WildFly 서버를 시작할 때 로그 SQL 문 "SET autocommit = 1"에서 볼 수 있습니다. @Transactional 주석은 DB 수준에서도이 처리 트랜잭션을 처리해야합니까?
저는 spring-boot, hibernate 및 MySQL jdbc를 사용하고 있습니다. 내가 MySQL의 InnoDB 테이블을 사용하고
15:00:54,060 DEBUG default task-12 jta.JtaTransactionManager:367 - Creating new transaction with name [com.example.test.TestServiceImpl.savePerson]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '',-java.lang.Exception
15:00:54,066 DEBUG default task-12 support.DefaultListableBeanFactory:251 - Returning cached instance of singleton bean 'transactionManager'
15:00:54,067 DEBUG default task-12 jta.JtaTransactionManager:476 - Participating in existing transaction
15:00:54,083 INFO default task-12 stdout:71 - Hibernate: insert into person (age, first_name, last_name) values (?, ?, ?)
15:00:54,125 DEBUG default task-12 jta.JtaTransactionManager:476 - Participating in existing transaction
15:00:54,126 INFO default task-12 stdout:71 - Hibernate: insert into person (age, first_name, last_name) values (?, ?, ?)
15:00:54,134 WARN default task-12 spi.SqlExceptionHelper:129 - SQL Error: 1062, SQLState: 23000
15:00:54,135 ERROR default task-12 spi.SqlExceptionHelper:131 - Duplicate entry 'John' for key 'idx_first_name_unique'
15:00:54,137 DEBUG default task-12 jta.JtaTransactionManager:858 - Participating transaction failed - marking existing transaction as rollback-only
15:00:54,137 DEBUG default task-12 jta.JtaTransactionManager:1074 - Setting JTA transaction rollback-only
15:00:54,138 DEBUG default task-12 support.DefaultListableBeanFactory:251 - Returning cached instance of singleton bean 'entityManagerFactory'
15:00:54,140 DEBUG default task-12 jta.JtaTransactionManager:851 - Initiating transaction rollback
CONSOLE.LOG. 다음은 서버 로그의 (결코 COMMIT, 아니 SET 자동 커밋 = 0, 아니 ROLLBACK ???) 식별자 # 22과 동일한 연결에서이 :
set autocommit = 0
insert into ...
insert into ...
rollback
:
대신 22 Connect [email protected] as anonymous on test
22 Query /* mysql-connector-java-6.0.6 (Revision: 3dab84f4d9bede3cdd14d57b99e9e98a02a5b97d) */SELECT @@session.auto_increment_increment AS auto_increment_increment, @@character_set_client AS character_set_client, @@character_set_connection AS character_set_connection, @@character_set_results AS character_set_results, @@character_set_server AS character_set_server, @@init_connect AS init_connect, @@interactive_timeout AS interactive_timeout, @@license AS license, @@lower_case_table_names AS lower_case_table_names, @@max_allowed_packet AS max_allowed_packet, @@net_buffer_length AS net_buffer_length, @@net_write_timeout AS net_write_timeout, @@query_cache_size AS query_cache_size, @@query_cache_type AS query_cache_type, @@sql_mode AS sql_mode, @@system_time_zone AS system_time_zone, @@time_zone AS time_zone, @@tx_isolation AS tx_isolation, @@wait_timeout AS wait_timeout
22 Query SELECT @@session.autocommit
22 Query SET NAMES utf8mb4
22 Query SET character_set_results = NULL
22 Query SET collation_connection = utf8_general_ci
22 Query SET autocommit=1
22 Query SET sql_mode='NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES'
22 Query SET autocommit=1
170424 15:02:07 22 Query SHOW FULL TABLES FROM `test` LIKE '%'
22 Query SHOW FULL TABLES FROM `test` LIKE '%'
22 Query SHOW FULL COLUMNS FROM `person` FROM `test` LIKE '%'
22 Query SHOW INDEX FROM `person` FROM `test`
170424 15:02:24 22 Query SELECT 1
22 Query insert into person (age, first_name, last_name) values (40, 'John', 'Smith')
22 Query insert into person (age, first_name, last_name) values (40, 'John', 'Smith')
는 다음과 같이 없어야합니다 TestServiceImpl.java
package com.example.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.test.Person;
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestRepository testRepository;
@Override
@Transactional(rollbackFor = Exception.class)
public void savePerson() {
Person p1 = new Person("John", "Smith", 40);
Person p2 = new Person("John", "Smith", 40);
testRepository.save(p1);
testRepository.save(p2);
}
}
TestService.java
package com.example.test;
public interface TestService {
public void savePerson();
}
,
TestRepository.java :
package com.example.test;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TestRepository extends JpaRepository<Person, Integer>{
}
Application.java :
package com.example.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Person.java 버전
package com.example.test;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Index;
@Entity
@Table(name = "PERSON", indexes = { @Index(name = "idx_first_name_unique", columnList = "first_name", unique = true), })
public class Person {
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "age")
private Integer age;
public Person() {
}
public Person(String firstname, String lastname, Integer age) {
this.firstName = firstname;
this.lastName = lastname;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName
+ ", age=" + age + "]";
}
}
POM 종속성 :
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.2.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.5.2.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
application.properties는 : 잠시 파고 후
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57InnoDBDialect
API 호출 JDBC 연결'setAutoCommit (false)'를 사용하여 트랜잭션을 시작합니다. 'START TRANSACTION'이 표시되지 않는 이유는 JDBC 드라이버가 이전 MySQL 버전 https://github.com/mysql/mysql-connector-j와의 하위 호환성으로부터'SET autocommit = 0' 남은 것으로 남겨두고 있기 때문입니다 /blob/6.0.6/src/main/java/com/mysql/cj/jdbc/ConnectionImpl.java#L3773 – coladict
또한 MySQL의 경우 테이블에 사용중인 스토리지 엔진이 무엇인지 중요합니다. InnoDB와 NDB 만 트랜잭션을 지원합니다. https://dev.mysql.com/doc/refman/5.5/en/storage-engines.html – coladict
해명 해 주셔서 감사합니다. 하지만 여전히, WildFly를 시작할 때 MySQL 서버 로그에는 "SET autocommit = 1"만 표시됩니다. "SET autocommit = 0"이 아닌가요? 어쨌든 트랜잭션은 DB에서 롤백되지 않습니다. autocommit을 true로 설정하면 자동으로 하나의 트랜잭션으로 실행된다는 것을 알 수 있습니다. DB 수준에서도 트랜잭션을 수행하는 방법을 모르겠습니다. –