enter image description hereorg.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session : [com.classroom.classroom.model.Student#7]; nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.classroom.classroom.model.Student#7]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:400) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionPosjaspaible.jpframework.jpa at org.springframework.orm.jpaDialect.translateExceptionPosjaspaible(springframeJpa)Jiframe: .doCommit(JpaTransactionManager.java:566) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commitr71(AbstractPlatformTransactionManager.java:743) at org.springframework.transaction.support.AbstractPlatformTransactionManagerManager.commit. springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407) at org.springframeinterketerworkinterceptor. java:119) at org.spring framework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springvocationframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) at org.spring.springframeworkprolectiveMethodRecedInvoke. java:186) at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) at org.springframeprolectivework.java:174 at org.springframeworkwork. .springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframeworkmicyopykAvodnaJ. .java:215) at jdk.proxy4/jdk.proxy4.$Proxy98.save(Unknown Source) at com.classroom.classroom.service.StudentService.saveOrUpdate(StudentService.java:33) at com.classroom.classroom.controller.StudentController.saveStudent(StudentController.java:62) at java.base/jdk.internal.reflect.NativeIthodAccessor invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoked.invoke:43. base/java.lang.reflect.Method.invoke(Method.java:568) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) at org.springframework.web.method.support. InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java.spring.org. RequestMappingHandlerAdapter.invokeHandlerMetho d(RequestMappingHandlerAdapter.java:894) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) at org.springframework.webtract.methodler.mvd AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) atwork.org. .servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilter(Application. java:227) at org.apache.cata lina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterFilterChilterChainternalChinternal java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework. .OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain(16) org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.apacheter.FilterAcaterin Applic ationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncoding:springframework.java1). .filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter2Filter ) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.auAuthenticator invoke(AuthenticatorBase.java:542) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java.orgapache) at .catalina.core.StandardEngineValve.invoke(Sta ndardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) at org.apache.coy .AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) at org.apache.tomcat.util.net.NioEndpoint$SocketNectionHandler.doRun( :1707) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) at java.base/ java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang. Thread.run(Thread.java:833) Caused by: javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.classroom.classroom.model.Student#7]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:123) at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181) at org.hibernate.internal.ExceptionConverterImpl.convaer(1) ) at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1366) at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:453) at org.hibernate.internal.SessionImplvaCompleshBefore. 3212) at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2380) at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.48) at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl48. .jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoplordinator cess$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLovacalImTransmitCoordin.in.) (TransactionImpl.java:101) at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) … 66 more

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="STUDENT")
public class Student {

    @Id
    @Column(name = "student_number") 
    private Long number;
    
    @Column  
    private String name;
    
    @Column  
    private String lastname;
   
}

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="CLASSROOM")
@JsonIdentityInfo(
           generator = ObjectIdGenerators.PropertyGenerator.class,
           property = "id")
public class Classroom {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "classroom_id")
    private Long id;
    
    @Column
    private String teatcher;
    
     @Column  
     private long level;
     
     
     @OneToMany(cascade=CascadeType.ALL)
        @JoinTable(
                name = "classroom_student",
                joinColumns = @JoinColumn(name = "classroom_id"),
                inverseJoinColumns = @JoinColumn(name = "student_number")
        )
     private Set<Student> student;

}

public interface StudentRepository extends CrudRepository<Student, Long>   {

}

public interface ClassroomRepository extends CrudRepository<Classroom, Long>   {

    
     @Query("SELECT c FROM Classroom c WHERE c.level = ?1")
     Classroom findByLevel(@Param("level") Long level);

}

@Service
public class StudentService {

    
    @Autowired  
    StudentRepository studentRepository;  
    public void saveOrUpdate(Player player)   
    {  
        playerRepository.save(player);  
    }  
}

@Service
public class ClassroomService {

    
    @Autowired  
    ClassroomRepository classroomRepository;  

public void saveOrUpdate(Classroom classroom)   
    {  
        classroomRepository.save(classroom);  
    }  

public Classroom findByYear(Long level) {
        return classroomRepository.findByLevel(level);
    } 
}


@RestController
public class StudentController {

    
    @Autowired  
    StudentService studentService;  
    
    @Autowired
    ClassroomService classroomService;
  
@PostMapping("/classroom/{level}")
    public ResponseEntity<String> saveStudent(@RequestBody Student student, @PathVariable long level)   
    {  
    
        try {
            Classroom classroom = classroomService.findByYear(level);

            classroom.getStudent().add(student);

            studentService.saveOrUpdate(student);
           return new ResponseEntity<>("Student saved successfully..", HttpStatus.CREATED);
        }catch (Exception ex){
            ex.printStackTrace();
            return new ResponseEntity<>("Error in saving Student ..", HttpStatus.BAD_REQUEST);
        }  
    }

}

@RestController
public class ClassroomController {

    
    @Autowired  
    ClassroomService classroomService;  

@PostMapping("/classroom")  
    private long saveTeam(@RequestBody Classroom classroom)   
    {  
        classroomService.saveOrUpdate(classroom);  
    return classroom.getId();  
    }
}

Al_Dedian is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

2