>source

Hibernate는 다른 데이터베이스에 데이터베이스에 두 번 저장되어있는 데이터가 다른 데이터베이스에서 두 번 저장되어 있지만 한 번만 데이터베이스에도 두 번 데이터를 저장합니다.

여기 내 도메인 클래스가 있습니다.

userdomain :

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDomain {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private int userId;
    private String firstName;
    private String lastName;
    private String userName;
    private String email;
    private String password;
    private boolean isEnabled= true;
    @OneToMany(cascade= CascadeType.ALL , fetch= FetchType.EAGER , mappedBy= "userDomain")
    @JsonIgnore
    private Set<UserRoleDomain> userRoleDomains= new HashSet<>();
}

roleedomain :

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RoleDomain {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private int roleId;
    private String name;
    @OneToMany(cascade= CascadeType.ALL, fetch= FetchType.LAZY, mappedBy= "roleDomain")
    private Set<UserRoleDomain> userRoleDomains= new HashSet<>();
}

userroledomain :

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserRoleDomain {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private int userRoleid;
    @ManyToOne(cascade=CascadeType.ALL ,  fetch= FetchType.EAGER)
    private UserDomain userDomain ;
    @ManyToOne
    private RoleDomain roleDomain ;
}

아래의 서비스 클래스를 보여주는

userService :

public MessageDto add(UserDto userDto , Set<UserRoleDomain> userRoles)
    {
             UserDomain userDomain= mapUserDtoToDomain(userDto);
            if( userRepository.findByUserName(userDomain.getUserName())!=null)
            {
                String responseMessage= "User is already register with name ! "+userDomain.getUserName();
                MessageDto messageDto= new MessageDto(responseMessage);
                log.info(responseMessage);
                return messageDto;
            }
            else {
                for (UserRoleDomain userRoleDomain: userRoles) {
                    roleRepository.saveAndFlush(userRoleDomain.getRoleDomain());
                }
                userDomain.getUserRoleDomains().addAll(userRoles);
                userRepository.saveAndFlush(userDomain);
                String responseMessage= "User has been added with Id " + userDomain.getUserId();
                MessageDto messageDto= new MessageDto(responseMessage);
                log.info(responseMessage);
                return messageDto;
            }
    }

Roleservice :

@Autowired
    private UserService userService;
    public Set<UserRoleDomain> add(UserDto userDto) {
        Set<UserRoleDomain> userRoles= new HashSet<>();
        RoleDomain roleDomain= new RoleDomain();
        roleDomain.setName("NORMAL");
        UserRoleDomain userRoleDomain= new UserRoleDomain();
        userRoleDomain.setRoleDomain(roleDomain);
        userRoleDomain.setUserDomain(userService.mapUserDtoToDomain(userDto));
        userRoles.add(userRoleDomain);
        return userRoles;
    }

userController 을 통해 서비스 호출


    @PostMapping("/add")
    public MessageDto addUser(@RequestBody UserDto userDto)
    {
        log.info("Post call have been received at user/add with DTO " + userDto);
        return userService.add(userDto , roleService.add(userDto));
    }

스프링 터미널 :

2021-07-19 22:09:16.436  INFO 3854 ---[           main] c.e.e.ExamPortalApiApplication           : Starting ExamPortalApiApplication using Java 11.0.10 on rohail-machine with PID 3854 (/media/rohail/hard hdd/ExamPortal/target/classes started by rohail in /media/rohail/hard hdd/ExamPortal)
2021-07-19 22:09:16.438  INFO 3854 ---[           main] c.e.e.ExamPortalApiApplication           : No active profile set, falling back to default profiles: default
2021-07-19 22:09:17.173  INFO 3854 ---[           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-07-19 22:09:17.212  INFO 3854 ---[           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 33 ms. Found 2 JPA repository interfaces.
2021-07-19 22:09:17.573  INFO 3854 ---[           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8888 (http)
2021-07-19 22:09:17.580  INFO 3854 ---[           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-07-19 22:09:17.581  INFO 3854 ---[           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.48]
2021-07-19 22:09:17.648  INFO 3854 ---[           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-07-19 22:09:17.648  INFO 3854 ---[           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1107 ms
2021-07-19 22:09:17.802  INFO 3854 ---[           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-07-19 22:09:17.851  INFO 3854 ---[           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-07-19 22:09:17.990  INFO 3854 ---[           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-07-19 22:09:18.071  INFO 3854 ---[           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 -Starting...
2021-07-19 22:09:18.205  INFO 3854 ---[           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 -Start completed.
2021-07-19 22:09:18.218  INFO 3854 ---[           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2021-07-19 22:09:18.678 DEBUG 3854 ---[           main] org.hibernate.SQL                        : alter table UserRoleDomain add constraint FK7bu6p1ewtda4yfcem34nieabb foreign key (roleDomain_roleId) references RoleDomain (roleId)
Hibernate: alter table UserRoleDomain add constraint FK7bu6p1ewtda4yfcem34nieabb foreign key (roleDomain_roleId) references RoleDomain (roleId)
2021-07-19 22:09:18.702 DEBUG 3854 ---[           main] org.hibernate.SQL                        : alter table UserRoleDomain add constraint FK68w0n83gh9ub79iycwq8idomm foreign key (userDomain_userId) references UserDomain (userId)
Hibernate: alter table UserRoleDomain add constraint FK68w0n83gh9ub79iycwq8idomm foreign key (userDomain_userId) references UserDomain (userId)
2021-07-19 22:09:18.717  INFO 3854 ---[           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-07-19 22:09:18.723  INFO 3854 ---[           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-07-19 22:09:19.074  WARN 3854 ---[           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-07-19 22:09:19.331  INFO 3854 ---[           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8888 (http) with context path ''
2021-07-19 22:09:19.339  INFO 3854 ---[           main] c.e.e.ExamPortalApiApplication           : Started ExamPortalApiApplication in 3.788 seconds (JVM running for 5.116)
2021-07-19 22:09:52.470  INFO 3854 ---[nio-8888-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-07-19 22:09:52.470  INFO 3854 ---[nio-8888-exec-2] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2021-07-19 22:09:52.471  INFO 3854 ---[nio-8888-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
2021-07-19 22:09:52.562  INFO 3854 ---[nio-8888-exec-2] c.e.e.controller.UserController          : Post call have been received at user/add with DTO UserDto(userId=0, firstName=Aliyan, lastName=Amir, userName=aliyan222, password=1122, isEnabled=true, userRoles=[])
2021-07-19 22:09:52.696 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : select userdomain0_.userId as userid1_1_, userdomain0_.email as email2_1_, userdomain0_.firstName as firstnam3_1_, userdomain0_.isEnabled as isenable4_1_, userdomain0_.lastName as lastname5_1_, userdomain0_.password as password6_1_, userdomain0_.userName as username7_1_ from UserDomain userdomain0_ where userdomain0_.userName=?
Hibernate: select userdomain0_.userId as userid1_1_, userdomain0_.email as email2_1_, userdomain0_.firstName as firstnam3_1_, userdomain0_.isEnabled as isenable4_1_, userdomain0_.lastName as lastname5_1_, userdomain0_.password as password6_1_, userdomain0_.userName as username7_1_ from UserDomain userdomain0_ where userdomain0_.userName=?
2021-07-19 22:09:52.699 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] -[aliyan222]
2021-07-19 22:09:52.717 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : select next_val as id_val from hibernate_sequence for update
Hibernate: select next_val as id_val from hibernate_sequence for update
2021-07-19 22:09:52.719 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : update hibernate_sequence set next_val= ? where next_val=?
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
2021-07-19 22:09:52.738 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : insert into RoleDomain (name, roleId) values (?, ?)
Hibernate: insert into RoleDomain (name, roleId) values (?, ?)
2021-07-19 22:09:52.739 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] -[NORMAL]
2021-07-19 22:09:52.739 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [INTEGER] -[5]
2021-07-19 22:09:52.748 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : select next_val as id_val from hibernate_sequence for update
Hibernate: select next_val as id_val from hibernate_sequence for update
2021-07-19 22:09:52.749 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : update hibernate_sequence set next_val= ? where next_val=?
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
2021-07-19 22:09:52.753 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : select next_val as id_val from hibernate_sequence for update
Hibernate: select next_val as id_val from hibernate_sequence for update
2021-07-19 22:09:52.755 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : update hibernate_sequence set next_val= ? where next_val=?
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
2021-07-19 22:09:52.758 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : select next_val as id_val from hibernate_sequence for update
Hibernate: select next_val as id_val from hibernate_sequence for update
2021-07-19 22:09:52.759 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : update hibernate_sequence set next_val= ? where next_val=?
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
2021-07-19 22:09:52.763 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : insert into UserDomain (email, firstName, isEnabled, lastName, password, userName, userId) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into UserDomain (email, firstName, isEnabled, lastName, password, userName, userId) values (?, ?, ?, ?, ?, ?, ?)
2021-07-19 22:09:52.764 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] -[null]
2021-07-19 22:09:52.764 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] -[Aliyan]
2021-07-19 22:09:52.765 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [BOOLEAN] -[true]
2021-07-19 22:09:52.765 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [4] as [VARCHAR] -[Amir]
2021-07-19 22:09:52.765 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [5] as [VARCHAR] -[1122]
2021-07-19 22:09:52.766 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [6] as [VARCHAR] -[aliyan222]
2021-07-19 22:09:52.766 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [7] as [INTEGER] -[6]
2021-07-19 22:09:52.767 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : insert into UserDomain (email, firstName, isEnabled, lastName, password, userName, userId) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into UserDomain (email, firstName, isEnabled, lastName, password, userName, userId) values (?, ?, ?, ?, ?, ?, ?)
2021-07-19 22:09:52.768 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] -[null]
2021-07-19 22:09:52.768 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] -[Aliyan]
2021-07-19 22:09:52.768 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [BOOLEAN] -[true]
2021-07-19 22:09:52.768 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [4] as [VARCHAR] -[Amir]
2021-07-19 22:09:52.768 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [5] as [VARCHAR] -[1122]
2021-07-19 22:09:52.768 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [6] as [VARCHAR] -[aliyan222]
2021-07-19 22:09:52.769 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [7] as [INTEGER] -[8]
2021-07-19 22:09:52.771 DEBUG 3854 ---[nio-8888-exec-2] org.hibernate.SQL                        : insert into UserRoleDomain (roleDomain_roleId, userDomain_userId, userRoleid) values (?, ?, ?)
Hibernate: insert into UserRoleDomain (roleDomain_roleId, userDomain_userId, userRoleid) values (?, ?, ?)
2021-07-19 22:09:52.772 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [INTEGER] -[5]
2021-07-19 22:09:52.772 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [INTEGER] -[8]
2021-07-19 22:09:52.772 TRACE 3854 ---[nio-8888-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [INTEGER] -[7]
2021-07-19 22:09:52.779  INFO 3854 ---[nio-8888-exec-2] c.e.examportalapi.service.UserService    : User has been added with Id 6

나쁜 아이디어 인 엔티티에 대해 @Data를 사용하지 마십시오 (deinum.biz/2019-02-13-lombok-data-ojects-entiaties 참조). 여러 트랜잭션에서 일을하고 있으며 DTO에서 두 번 사용자를 만드는 것입니다. 그래서 그렇습니다. 그렇습니다. 두 번 저장됩니다. 기본적으로 전체 등록 code가 너무 복잡하고 오류가 발생하기 쉽습니다.

M. Deinum2021-07-21 11:16:08

그러나 그게 당신이 두 번 사용자를 만드는 방법입니다.

Rohail Iqbal2021-07-21 11:16:08

여기에서는 UserRoledomain에 참여하는 클래스가있는 사용자와 역할을 맵핑했습니다 .... 내 매핑 주석에 문제가 있습니까?

Rohail Iqbal2021-07-21 11:16:08

매핑은 괜찮습니다. 문제는 code와 일을 삽입하는 방법입니다. 지나치게 복잡한 첨가 등을 명시한 것처럼 범인입니다.

M. Deinum2021-07-21 11:16:08

이 솔루션은 무엇입니까?

Rohail Iqbal2021-07-20 11:31:28
  • 이전 Perl 모든 필드를 보는 방법
  • 다음 reactjs : 반응 /재료 UI가있는 여러 DIV 및 입력 값 추가