Relacje i kolejność zapisu

0

Zaczne od tego,że dostaje poniższy błąd z kolejnoscią zapisu i prośba żebyście mi coś podpowiedzieli jak powinienem to napisać żeby poszło (poniżej kody,klas i metoda):

 
2016-05-28 12:20:19.390  WARN 1284 --- [nio-8080-exec-8] o.h.a.i.UnresolvedEntityInsertActions    : HHH000437: Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity. The unsaved transient entity must be saved in an operation prior to saving these dependent entities.
	Unsaved transient entity: ([pl.cms.model.PlaceBD#<null>])
	Dependent entities: ([[pl.cms.model.ExchangeBD#<null>]])
	Non-nullable association(s): ([pl.cms.model.ExchangeBD.place])
2016-05-28 12:20:19.390  WARN 1284 --- [nio-8080-exec-8] o.h.a.i.UnresolvedEntityInsertActions    : HHH000437: Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity. The unsaved transient entity must be saved in an operation prior to saving these dependent entities.
	Unsaved transient entity: ([pl.cms.model.CarBD#<null>])
	Dependent entities: ([[pl.cms.model.ExchangeBD#<null>]])
	Non-nullable association(s): ([pl.cms.model.ExchangeBD.car])
2016-05-28 12:20:19.403 ERROR 1284 --- [nio-8080-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Not-null property references a transient value - transient instance must be saved before current operation : pl.cms.model.ExchangeBD.place -> pl.cms.model.PlaceBD; nested exception is org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : pl.cms.model.ExchangeBD.place -> pl.cms.model.PlaceBD] with root cause

org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : pl.cms.model.ExchangeBD.place -> pl.cms.model.PlaceBD
	at org.hibernate.action.internal.UnresolvedEntityInsertActions.checkNoUnresolvedActionsAfterOperation(UnresolvedEntityInsertActions.java:137) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
	at org.hibernate.engine.spi.ActionQueue.checkNoUnresolvedActionsAfterOperation(ActionQueue.java:320) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
	at org.hibernate.internal.SessionImpl.checkNoUnresolvedActionsAfterOperation(SessionImpl.java:658) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
	at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:686) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
	at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:676) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
	at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:671) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
	at pl.cms.dao.GenericDaoImpl.saveOrUpdate(GenericDaoImpl.java:41) ~[classes/:na]
	at pl.cms.dao.GenericDaoImpl$$FastClassBySpringCGLIB$$756cf9ee.invoke(<generated>) ~[classes/:na]
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.2.4.RELEASE.jar:4.2.4.RELEASE]
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
	at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.2.4.RELEASE.jar:4.2.4.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
	at pl.cms.dao.ExchangeDaoHibImpl$$EnhancerBySpringCGLIB$$bb8241f2.saveOrUpdate(<generated>) ~[classes/:na]
	at pl.cms.service.ExchangeServiceImpl.saveOrUpdate(ExchangeServiceImpl.java:27) ~[classes/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_25]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_25]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_25]
	at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_25]
	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]

Teraz pokaże Wam relację jaka wystepuje miedzy klasami ,metodę controllera oraz moją metodę ajax.

 
@Entity
@Table(name = "Samochody")
public class CarBD {

    @Setter
    @Getter
    @JsonIgnore
    @OneToMany(fetch = FetchType.LAZY,mappedBy = "car",cascade = CascadeType.ALL)
    private List<ExchangeBD> exchangeList = new ArrayList<>();

}
--------------------------------------------------
@Entity
@Table(name = "Wymiany")
public class ExchangeBD {

    @Setter
    @Getter
    @ManyToOne
    @JoinColumn(name = "car")
    @NotNull
    private CarBD car;

}

METODA CONTROLLERA --------------------------------------------------

 
    @RequestMapping(value = "addExchange",method = RequestMethod.POST,produces = "application/json")
    public ResponseEntity<ExchangeBD> addExchange(@RequestBody ExchangeBD exchange){
        exchangeService.saveOrUpdate(exchange);
        HttpStatus httpStatus = exchange !=null ? HttpStatus.CREATED : HttpStatus.CONFLICT;
        return new ResponseEntity<ExchangeBD>(exchange,httpStatus);
    }

METODA AJAX--------------------------------------------------

 var saveExchange = function(){
        var exchange = {
            "car": {'id':parseInt($('#carListSelect').get(0).id,10)},
            "exchangeDate": $('#exchangeDateInput').val(),
            "exchangePrice": $('#exchangePriceInput').val(),
            "exchangeDescription": $('#exchangeDescriptionInput').val(),
            "place": {'id':parseInt($('#placeListSelect').get(0).id,10)}
        };

        $.ajax({
            url: 'exchange/addExchange',
            type: 'POST',
            contentType:"application/json",
            data:  JSON.stringify(exchange),
            success: function () {
                alert("Dodano nową wymianę");
                $('#exchangeDateInput').val('');
                $('#exchangePriceInput').val('');
                $('#exchangeDescriptionInput').val('');
            },
            error: function (jqxhr, textStatus, error) {
                var err = textStatus + ", " + error;
                console.log( "Request Failed: " + err );
            }

        });

    };
0

Spróbuj dodać @ManyToOne(cascade = CascadeType.ALL)

0

Tam jest chyba inny problem tzn:
Samochod jest wybierany z listy:

Przechwytywanie.PNG

a metoda która wrzuca tam auta wygląda tak

 
 $.ajax({
        url:'car/carListForSelect',
        type:'GET',
        contentType: 'application/json;charset=UTF-8',
        success: function( data ) {
            $.each(data, function(i, value) {
                $('#carListSelect').append($('<option></option>`').text(value.carName).attr('value',value));
            });
        }
    });

do tej zmiennej nie trafia odpowiedni obiekt .

var exchange = {
            "car": {'id':parseInt($('#carListSelect').get(0).id,10)},
            "exchangeDate": $('#exchangeDateInput').val(),
            "exchangePrice": $('#exchangePriceInput').val(),
            "exchangeDescription": $('#exchangeDescriptionInput').val(),
            "place": {'id':parseInt($('#placeListSelect').get(0).id,10)}
        };
 

sss.PNG

W jaki sposób prawidłowo pobrać id z takiego option do tej zmiennej ?

1 użytkowników online, w tym zalogowanych: 0, gości: 1