작성
·
329
0
안녕하세요.
제가 멀 잘못 했길래 아래 결과가 모두 false 가 나오는거죠? (2.Result : true 가 나와야 한다고 생각 합니다.)
(Tester를 만들어 돌리는게 익숙치 않아 직접 돌렸습니다.)
소스는 test05() 수행 해서 Post table에 저장하고, 영속성컨텍스트에 관리 되는 Entity 가 어떤건지 확인 하는 코드 입니다.
package com.example.JPA03;
import com.example.JPA03.domain.Post;
import com.example.JPA03.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Component
public class JPA03Runner implements ApplicationRunner {
@Autowired
PostRepository postRepository;
@PersistenceContext
private EntityManager entityManager;
@Override
public void run(ApplicationArguments args) throws Exception {
test05();
}
@Transactional
private void test05(){
Post post = new Post();
post.setTitle("ys..");
Post savedPost = postRepository.save(post); // persist
System.out.println("1. result : " + entityManager.contains(post) );
System.out.println("2. result : " + entityManager.contains(savedPost) );
}
}
package com.example.JPA03.domain;
import com.example.JPA03.event.PostPublishedEvent;
import org.springframework.data.domain.AbstractAggregateRoot;
import javax.persistence.*;
import java.util.Date;
@Entity//@NamedQuery(name="Post.testNamedQuery", query = "select * from Post as p where p.title = ?1")
public class Post extends AbstractAggregateRoot<Post> {
@Id @GeneratedValue
private Long id;
private String title;
private Integer likeCount;
@Temporal(TemporalType.TIMESTAMP)
private Date creatDate;
public Post publishPostEvent(){
this.registerEvent(new PostPublishedEvent(this));
return this;
}
public Integer getLikeCount() {
return likeCount;
}
public void setLikeCount(Integer likeCount) {
this.likeCount = likeCount;
}
public Date getCreatDate() {
return creatDate;
}
public void setCreatDate(Date creatDate) {
this.creatDate = creatDate;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
package com.example.JPA03;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Jpa03Application {
public static void main(String[] args) {
SpringApplication.run(Jpa03Application.class, args);
}
}
==수행 결과 ==
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.3.RELEASE)
2020-08-26 01:05:37.745 INFO 4260 --- [ main] com.example.JPA03.Jpa03Application : Starting Jpa03Application on DESKTOP-GOQMQQP with PID 4260 (D:\private\study\jpa_study\JPA03\target\classes started by BISTel in D:\private\study\jpa_study)
2020-08-26 01:05:37.748 INFO 4260 --- [ main] com.example.JPA03.Jpa03Application : No active profile set, falling back to default profiles: default
2020-08-26 01:05:38.147 INFO 4260 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-08-26 01:05:38.208 INFO 4260 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 52ms. Found 1 JPA repository interfaces.
2020-08-26 01:05:38.563 INFO 4260 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-26 01:05:38.597 INFO 4260 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-08-26 01:05:38.639 INFO 4260 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.20.Final
2020-08-26 01:05:38.662 INFO 4260 --- [ main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-08-26 01:05:38.749 INFO 4260 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-08-26 01:05:39.206 INFO 4260 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-08-26 01:05:39.296 INFO 4260 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-08-26 01:05:39.324 INFO 4260 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
2020-08-26 01:05:39.857 INFO 4260 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-08-26 01:05:39.862 INFO 4260 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-08-26 01:05:40.110 INFO 4260 --- [ main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-08-26 01:05:40.115 INFO 4260 --- [ main] com.example.JPA03.Jpa03Application : Started Jpa03Application in 2.661 seconds (JVM running for 3.051)
Hibernate:
select
nextval ('hibernate_sequence')
Hibernate:
insert
into
post
(creat_date, like_count, title, id)
values
(?, ?, ?, ?)
2020-08-26 01:05:41.837 TRACE 4260 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [TIMESTAMP] - [null]
2020-08-26 01:05:41.837 TRACE 4260 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [INTEGER] - [null]
2020-08-26 01:05:41.838 TRACE 4260 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARCHAR] - [ys..]
2020-08-26 01:05:41.838 TRACE 4260 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [BIGINT] - [66]
1. result : false
2. result : false
ㅇㅇ
답변 3
0
0
답변 감사합니다.
빠른 습득을 위해 부분 부분 학습을 하다보니 transaction 의 이해가 없었습니다.
Spring boot를 학습해야 할지요? Spring을 학습 해야 할지요?
0
private 메소드라서 @Transactional이 적용되지 않았고, 트랜잭션은 오직 save(post)를 메소드에만 적용이 됐습니다. 왜냐면 save()를 구현한 SiimpleJpaRepository가 @Transactional이 가지고 있거든요.
@Transactional 애노테이션을 JPA03Runner 클래스 위로 옮기세요. public으로 고쳐도 문제인게.. 프록시 기반의 AOP는 프록시 객체 내부에서 다른 메소드를 호출하는 경우에 AOP가 적용되지 않아요. 그래서 @Transactional을 최초에 호출되는 public 메소드에 붙이거나, 클래스에 붙여두시면 해당 클래스에 속한 모든 public 메소드에 적용이 되오니 편하신 대로 쓰시면 됩니다.
이 문제를 해결하지 못하신거 보면 스프링의 트랜잭션 처리와 스프링 AOP에 대한 이해가 더 필요할 것으로 보입니다. 그쪽으로 조금 더 공부해 보시면 좋을거 같아요.