영속성 컨텍스트에 의해 관리되는 entity 확인 시 오작동 문의
401
작성한 질문수 14
안녕하세요.
제가 멀 잘못 했길래 아래 결과가 모두 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
답변 감사합니다.
빠른 습득을 위해 부분 부분 학습을 하다보니 transaction 의 이해가 없었습니다.
Spring boot를 학습해야 할지요? Spring을 학습 해야 할지요?
0
private 메소드라서 @Transactional이 적용되지 않았고, 트랜잭션은 오직 save(post)를 메소드에만 적용이 됐습니다. 왜냐면 save()를 구현한 SiimpleJpaRepository가 @Transactional이 가지고 있거든요.
@Transactional 애노테이션을 JPA03Runner 클래스 위로 옮기세요. public으로 고쳐도 문제인게.. 프록시 기반의 AOP는 프록시 객체 내부에서 다른 메소드를 호출하는 경우에 AOP가 적용되지 않아요. 그래서 @Transactional을 최초에 호출되는 public 메소드에 붙이거나, 클래스에 붙여두시면 해당 클래스에 속한 모든 public 메소드에 적용이 되오니 편하신 대로 쓰시면 됩니다.
이 문제를 해결하지 못하신거 보면 스프링의 트랜잭션 처리와 스프링 AOP에 대한 이해가 더 필요할 것으로 보입니다. 그쪽으로 조금 더 공부해 보시면 좋을거 같아요.
spring boot 2.7.13-SNAPSHOT trace 소문자 로그 안나옴
0
532
1
<스프링 데이터 Common: 기본 리포지토리 커스터마이징> 에 대한 질문
0
392
1
comment table에서 저장될떄 왜 id값이 2부터저장이되는건가요?
0
407
1
@EnableJpaRepositories 설정을 스프링부트가 어디에서 자동설정하나요?
0
450
0
PersistenceContext 관련 질문드립니다.
0
335
1
지금(Eager), 나중에(Lazy)의 의미를 모르겠습니다
0
338
1
transaction 구간이 길어질 경우의 처리방법 문의드립니다.
0
905
1
docker postgres
0
292
1
Multiple DataSource 사용 시 transaction 관련 질문 드립니다.
0
2908
1
entity 중 null이 아닌 필드만 update 할 방법이 있을까요?
0
1190
1
Eager 모드일 경우, join을 inner join으로 바꾸는 법이 있을까요?
0
385
1
엔티티를 상속받는 DTO가 일반적인가요?
1
1847
1
커스텀 타입 클래스를 String 타입 처럼 이용해 쿼리하는 방법에 대해 질문하고 싶습니다.
0
339
1
연관관계 매핑 어떤식으로 해야될지 감이 안잡힙니다.
0
566
4
EntityManager 주입시 Annotation관련 질문드립니다.
0
565
1
클래스 기반 프로젝션 사용 관련 질문
0
560
1
save 메서드 질문드립니다.
0
258
1
복잡한 통계쿼리도 JPA로 가능한가요?
2
5592
1
find 와 get의 차이가 무엇인가요?
0
890
1
실무에서 JPA 할 때 FK로 개발할때 연관관계를 꼭 맺어주어야 하나요?
0
998
1
\dt Did not find any relations.
0
481
1
소스코드는 어디서 볼 수 있을까요?
1
287
1
table 생성과 select 문에 대한 질문
0
174
1
스프링 데이터 RepositoryTest 관련 질문
0
2173
2





