트랜잭션 주석이 Spring Boot에서 작동하지 않음
@Spring Boot에서 트랜잭션이 작동하지 않습니다.
Application.java:
@EnableTransactionManagement(proxyTargetClass=true)
@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class})
public class Application {
@Autowired
private EntityManagerFactory entityManagerFactory;
public static void main(String[] args) {
System.out.println("--------------------------- Start Application ---------------------------");
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
@Bean
public SessionFactory getSessionFactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.buhryn.interviewer.models" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/interviewer");
dataSource.setUsername("postgres");
dataSource.setPassword("postgres");
return dataSource;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.setProperty("hibernate.show_sql", "false");
properties.setProperty("hibernate.format_sql", "false");
properties.setProperty("hibernate.hbm2ddl.auto", "create");
properties.setProperty("hibernate.current_session_context_class", "org.hibernate.context.internal.ThreadLocalSessionContext");
return properties;
}
}
다오자바 후보
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
public class CandidateDao implements ICandidateDao{
@Autowired
SessionFactory sessionFactory;
protected Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
@Override
@Transactional
public CandidateModel create(CandidateDto candidate) {
CandidateModel candidateModel = new CandidateModel(candidate.getFirstName(), candidate.getLastName(), candidate.getEmail(), candidate.getPhone());
getCurrentSession().save(candidateModel);
return candidateModel;
}
@Override
public CandidateModel show(Long id) {
return new CandidateModel(
"new",
"new",
"new",
"new");
}
@Override
public CandidateModel update(Long id, CandidateDto candidate) {
return new CandidateModel(
"updated",
candidate.getLastName(),
candidate.getEmail(),
candidate.getPhone());
}
@Override
public void delete(Long id) {
}
}
서비스 클래스
@Service
public class CandidateService implements ICandidateService{
@Autowired
ICandidateDao candidateDao;
@Override
public CandidateModel create(CandidateDto candidate) {
return candidateDao.create(candidate);
}
@Override
public CandidateModel show(Long id) {
return candidateDao.show(id);
}
@Override
public CandidateModel update(Long id, CandidateDto candidate) {
return candidateDao.update(id, candidate);
}
@Override
public void delete(Long id) {
candidateDao.delete(id);
}
}
Controller.class
@RestController
@RequestMapping(value = "/api/candidates")
public class CandidateController {
@Autowired
ICandidateService candidateService;
@RequestMapping(value="/{id}", method = RequestMethod.GET)
public CandidateModel show(@PathVariable("id") Long id) {
return candidateService.show(id);
}
@RequestMapping(method = RequestMethod.POST)
public CandidateModel create(@Valid @RequestBody CandidateDto candidate, BindingResult result) {
RequestValidator.validate(result);
return candidateService.create(candidate);
}
@RequestMapping(value="/{id}", method = RequestMethod.PUT)
public CandidateModel update(@PathVariable("id") Long id, @Valid @RequestBody CandidateDto candidate, BindingResult result) {
RequestValidator.validate(result);
return candidateService.update(id, candidate);
}
@RequestMapping(value="/{id}", method = RequestMethod.DELETE)
public void delete(@PathVariable("id") Long id) {
candidateService.delete(id);
}
}
DAO 시스템 스로우 예외에서 생성 메서드를 호출하는 경우:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: save is not valid without active transaction; nested exception is org.hibernate.HibernateException: save is not valid without active transaction
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:291)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
내 Gradle 파일:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
jar {
baseName = 'interviewer'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.codehaus.jackson:jackson-mapper-asl:1.9.13")
compile("com.google.code.gson:gson:2.3.1")
compile("org.springframework.data:spring-data-jpa:1.8.0.RELEASE")
compile("org.hibernate:hibernate-entitymanager:4.3.10.Final")
compile("postgresql:postgresql:9.1-901-1.jdbc4")
compile("org.aspectj:aspectjweaver:1.8.6")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
}
git 저장소 링크: https://github.com/Yurii-Buhryn/interviewer
먼저 Spring Boot을 사용한 후 Spring Boot을 사용하여 자동으로 구성할 수 있습니다.데이터 소스, 엔티티 관리자 공장, 트랜잭션 관리자 등을 구성합니다.
다음에는 잘못된 트랜잭션 관리자를 사용하고 있으므로 JPA를 사용해야 합니다.JpaTransactionManager
대신에HibernateTransactionManager
이미 구성되어 있으므로 빈 정의를 제거하면 됩니다.
두번째 너의hibernate.current_session_context_class
제대로 된 tx 통합을 망치고 있습니다. 제거하십시오.
자동 구성 사용
이 모든 것을 고려할 때 기본적으로 비용을 절감할 수 있습니다.Application
다음 항목으로 분류합니다.
@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class})
@EntityScan("com.buhryn.interviewer.models")
public class Application {
public static void main(String[] args) {
System.out.println("--------------------------- Start Application ---------------------------");
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
@Bean
public SessionFactory sessionFactory(EntityManagerFactory emf) {
if (emf.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return emf.unwrap(SessionFactory.class);
}
}
다음 추가application.properties
에src/main/resources
다음을 포함하는.
# DataSource configuration
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/interviewer
# General JPA properties
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=false
# Hibernate Specific properties
spring.jpa.properties.hibernate.format_sql=false
spring.jpa.hibernate.ddl-auto=create
이렇게 하면 데이터 소스와 JPA가 올바르게 구성됩니다.
일반 최대 절전 모드 대신 JPA 사용
일반적인 최대 절전 모드 API를 사용하는 대신 다른 팁은 JPA를 사용하여 콩을 제거할 수 있습니다.SessionFactory
뿐만 아니라.단순히 당신의 dao를 사용하도록 변경합니다.EntityManager
대신에SessionFactory
.
@Repository
public class CandidateDao implements ICandidateDao{
@PersistenceContext
private EntityManager em;
@Override
@Transactional
public CandidateModel create(CandidateDto candidate) {
CandidateModel candidateModel = new CandidateModel(candidate.getFirstName(), candidate.getLastName(), candidate.getEmail(), candidate.getPhone());
return em.persist(candidateModel);
}
@Override
public CandidateModel show(Long id) {
return new CandidateModel(
"new",
"new",
"new",
"new");
}
@Override
public CandidateModel update(Long id, CandidateDto candidate) {
return new CandidateModel(
"updated",
candidate.getLastName(),
candidate.getEmail(),
candidate.getPhone());
}
@Override
public void delete(Long id) {
}
}
스프링 데이터 JPA 추가
그리고 정말로 이점을 얻고 싶다면 스프링 데이터 JPA를 혼합물에 추가하고 DAO를 완전히 제거한 후 인터페이스만 남겨둡니다.현재 사용 중인 것은 서비스 클래스(IMHO에 속함)로 이동됩니다.
전체 저장소
public interface ICandidateDao extends JpaRepository<CandidateModel, Long> {}
수정된 서비스(이제는 트랜잭션도 해야 하며 모든 비즈니스 로직이 서비스에 포함됨).
@Service
@Transactional
public class CandidateService implements ICandidateService{
@Autowired
ICandidateDao candidateDao;
@Override
public CandidateModel create(CandidateDto candidate) {
CandidateModel candidateModel = new CandidateModel(candidate.getFirstName(), candidate.getLastName(), candidate.getEmail(), candidate.getPhone());
return candidateDao.save(candidate);
}
@Override
public CandidateModel show(Long id) {
return candidateDao.findOne(id);
}
@Override
public CandidateModel update(Long id, CandidateDto candidate) {
CandidateModel cm = candidateDao.findOne(id);
// Update values.
return candidateDao.save(cm);
}
@Override
public void delete(Long id) {
candidateDao.delete(id);
}
}
이제 다음에 대한 빈 정의도 제거할 수 있습니다.SessionFactory
축소Application
겨우main
방법.
@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class})
@EntityScan("com.buhryn.interviewer.models")
public class Application {
public static void main(String[] args) {
System.out.println("--------------------------- Start Application ---------------------------");
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
그래서 저는 틀을 이용해서 작업하는 것이 아니라 틀을 이용해서 작업하는 것을 강력히 제안하고 싶습니다.그러면 개발자 라이브가 정말 단순해집니다.
종속성
마지막으로, 저는 그것을 제거하는 것을 제안합니다.spring-data-jpa
종속성으로부터의 종속성을 확인하고 대신 스타터를 사용합니다.AspectJ도 마찬가지입니다. 이를 위해 AOP 스타터를 사용하십시오.또한 Jackson 1은 더 이상 지원되지 않으므로 종속성을 추가해도 아무것도 추가되지 않습니다.
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-aop")
compile("com.google.code.gson:gson:2.3.1")
compile("org.hibernate:hibernate-entitymanager:4.3.10.Final")
compile("postgresql:postgresql:9.1-901-1.jdbc4")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
언급URL : https://stackoverflow.com/questions/30870146/transactional-annotation-not-working-in-spring-boot
'programing' 카테고리의 다른 글
순수 C로 구현된 MVC (0) | 2023.06.25 |
---|---|
쿼리 주석을 사용하여 MongoRepository에서 항목을 삭제하는 방법은 무엇입니까? (0) | 2023.06.25 |
SQL Profiler에서 트리거 실행을 모니터링하는 방법 (0) | 2023.06.25 |
Git: 가져오기 전용 리모컨을 설정하시겠습니까? (0) | 2023.06.25 |
R이 할 수 없는 MATLAB이 할 수 있는 것은 무엇입니까? (0) | 2023.06.25 |