0

board entity and member entity is not association mapping

board entity class...

@Entity(name = "BOARD")
@Table
@SequenceGenerator(name = "BOARD_SEQ_GENERATOR"
                    , sequenceName = "BOARD_SEQ"
                    , initialValue = 1)
public class BoardEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE
                    , generator = "BOARD_SEQ_GENERATOR")
    private long idx;

    @Lob
    private String contents;

    private String title;

    private long insNo;

    @Temporal(TemporalType.TIMESTAMP)
    private Date insDate;

    private long uptNo;

    @Temporal(TemporalType.TIMESTAMP)
    private Date uptDate;

    @Transient
    private String insName;
    .....
    getter / setter

member entity class...

@Entity
@Table(name = "MEMBER")
@SequenceGenerator(name = "MEMBERIDX_SEQ_GENERATOR"
                    , sequenceName = "MEMBERIDX_SEQ"
                    , initialValue = 1)
public class MemberEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE
                    , generator = "MEMBERIDX_SEQ_GENERATOR")
    private long memberIdx;

    @Column(nullable = false)
    private String id;

    @Column(nullable = false)
    private String pwd;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private int age;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(nullable = false)
    private Date insDate;
    .....
    getter / setter

MemberRepository class code...

@Repository
public interface MemberRepository extends JpaRepository<MemberEntity, Long> {

    @Query("select m from MemberEntity m where m.id=:id")
    public MemberEntity getMemberIDbyId(@Param("id") String id);
}

MemberService class code...

@Service
@Transactional
public class MemberService {

    @Autowired private MemberRepository memberRepository;

    public void addMember(MemberEntity member) {
        memberRepository.save(member);
    }

    public MemberEntity getMember(Long memberIdx) {
        return memberRepository.getOne(memberIdx);
    }
}

BoardController class code...

@Controller
@RequestMapping(value = "/board")
public class BoardController {

    @Autowired 
    private BoardService boardService;

    @Autowired
    private MemberService memberService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String BoardList(HttpServletRequest req, HttpServletResponse resp, Model model) throws Exception {

        List<BoardEntity> resutlList = boardService.getBoardList();

        //resutlList.forEach(System.out::println);

        for (BoardEntity item : resutlList) {
            MemberEntity memberEntity = memberService.getMember(item.getInsNo());
            item.setInsName(memberEntity.getName());
        }

        model.addAttribute("boardList", resutlList);

        return "board/boardList";
    }
}

ErrorMessage

심각: Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session] with root cause org.hibernate.LazyInitializationException: could not initialize proxy - no Session at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:147) at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:260) at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:68) at com.knk.spring4.entity.member.MemberEntity_$$_jvst201_0.getName(MemberEntity_$$_jvst201_0.java) at com.knk.spring4.controller.board.BoardController.BoardList(BoardController.java:70) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)

ERD

The InsNo and UptNo columns in the Board table contain the MemberIdx values of the member who created and edited the post.

I want to import the ID column of the membership table using the InsNo column or the UptNo column of the bulletin board table.

How do I handle the current error if there is no mapping of associations?

1

1 Answer 1

3

It's because you are using the JpaRepository.getOne method to retrieve members. According to the JPA repository Javadoc :

T getOne(ID id)

Returns a reference to the entity with the given identifier.

See Also:

EntityManager.getReference(Class, Object)

And and the EntityManager Javadoc:

T getReference(Class entityClass, Object primaryKey)

Get an instance, whose state may be lazily fetched.

Basically JpaRepository.getOne doesn't return an object build from a fetched database record but a proxy referencing the record that will get initialize on the first access to any member other than the refering id. So when you call MemberEntity.getName when the Session/EntityManager you get the LazyException when the proxy try to fetch the record.

To fix it in your case you have multiple option:

  1. Using a OpenSessionInViewFilter to keep the session on the entire request, this one is an anti-pattern and not recommended
  2. You can use the Hibernate annotation @Lazy and set the lazy property to false (it works in other similar case, not sure it will works here). Cons here is the annotation is not a JPA's one, so you'll tie your project tot he implementation and not the specification.
  3. You can manually trigger the proxy when the Session/EntityManager is still open by calling any member.
  4. The CrudReposiroty.findOne method return the object and not a proxy if i remember correctly.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.