com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列'ID_LIEU'不能为null

时间:2016-05-24 17:59:03

标签: spring hibernate

当我尝试插入新旅行时,我得到那些红线。我正在使用Spring MVC,Hibernate和MySQL。任何人都可以帮我解决这个问题吗?

以下是代码:

Voyage.java:

@Entity
@Table(name = "voyage", catalog = "voyage")
public class Voyage implements java.io.Serializable {

    private Integer idVoyage;
    private Lieu lieuDepart;
    private Lieu lieuArrive;
    private Moyendetransport moyendetransport;
    private Date depart;
    private Date arrivee;
    private Set<Lignedetrips> lignedetripses = new HashSet<Lignedetrips>(0);

    public Voyage() {
    }

    public Voyage(Lieu lieuDepart, Lieu lieuArrive, Moyendetransport moyendetransport) {
        this.lieuDepart = lieuDepart;
        this.lieuArrive = lieuArrive;
        this.moyendetransport = moyendetransport;
    }

    public Voyage(Lieu lieuDepart, Lieu lieuArrive, Moyendetransport moyendetransport, Date depart, Date arrivee,
            Set<Lignedetrips> lignedetripses) {
        this.lieuDepart = lieuDepart;
        this.lieuArrive = lieuArrive;
        this.moyendetransport = moyendetransport;
        this.depart = depart;
        this.arrivee = arrivee;
        this.lignedetripses = lignedetripses;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = "ID_VOYAGE", unique = true, nullable = false)
    public Integer getIdVoyage() {
        return this.idVoyage;
    }

    public void setIdVoyage(Integer idVoyage) {
        this.idVoyage = idVoyage;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "LIE_ID_LIEU", nullable = false)
    public Lieu getlieuDepart() {
        return this.lieuDepart;
    }

    public void setlieuDepart(Lieu lieuDepart) {
        this.lieuDepart = lieuDepart;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ID_LIEU", nullable = false)
    public Lieu getlieuArrive() {
        return this.lieuArrive;
    }

    public void setlieuArrive(Lieu lieuArrive) {
        this.lieuArrive = lieuArrive;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ID_MOYENDETRANSPORT", nullable = false)
    public Moyendetransport getMoyendetransport() {
        return this.moyendetransport;
    }

    public void setMoyendetransport(Moyendetransport moyendetransport) {
        this.moyendetransport = moyendetransport;
    }

    @Temporal(TemporalType.DATE)
    @Column(name = "DEPART", length = 10)
    public Date getDepart() {
        return this.depart;
    }

    public void setDepart(Date depart) {
        this.depart = depart;
    }

    @Temporal(TemporalType.DATE)
    @Column(name = "ARRIVEE", length = 10)
    public Date getArrivee() {
        return this.arrivee;
    }

    public void setArrivee(Date arrivee) {
        this.arrivee = arrivee;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "voyage")
    public Set<Lignedetrips> getLignedetripses() {
        return this.lignedetripses;
    }

    public void setLignedetripses(Set<Lignedetrips> lignedetripses) {
        this.lignedetripses = lignedetripses;
    }

}`

Lieu.java

@Entity
@Table(name = "lieu", catalog = "voyage")
public class Lieu implements java.io.Serializable {

    private Integer idLieu;
    private String codepostal;
    private String ville;
    private String pays;
    private String gareAeroportPort;
    private Set<Voyage> voyagesForLieIdLieu = new HashSet<Voyage>(0);
    private Set<Voyage> voyagesForIdLieu = new HashSet<Voyage>(0);

    public Lieu() {
    }

    public Lieu(String codepostal, String ville, String pays, String gareAeroportPort, Set<Voyage> voyagesForLieIdLieu,
            Set<Voyage> voyagesForIdLieu) {
        this.codepostal = codepostal;
        this.ville = ville;
        this.pays = pays;
        this.gareAeroportPort = gareAeroportPort;
        this.voyagesForLieIdLieu = voyagesForLieIdLieu;
        this.voyagesForIdLieu = voyagesForIdLieu;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = "ID_LIEU", unique = true, nullable = false)
    public Integer getIdLieu() {
        return this.idLieu;
    }

    public void setIdLieu(Integer idLieu) {
        this.idLieu = idLieu;
    }

    @Column(name = "CODEPOSTAL", length = 6)
    public String getCodepostal() {
        return this.codepostal;
    }

    public void setCodepostal(String codepostal) {
        this.codepostal = codepostal;
    }

    @Column(name = "VILLE", length = 40)
    public String getVille() {
        return this.ville;
    }

    public void setVille(String ville) {
        this.ville = ville;
    }

    @Column(name = "PAYS", length = 40)
    public String getPays() {
        return this.pays;
    }

    public void setPays(String pays) {
        this.pays = pays;
    }

    @Column(name = "GARE_AEROPORT_PORT", length = 100)
    public String getGareAeroportPort() {
        return this.gareAeroportPort;
    }

    public void setGareAeroportPort(String gareAeroportPort) {
        this.gareAeroportPort = gareAeroportPort;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "lieuDepart")
    public Set<Voyage> getVoyagesForLieIdLieu() {
        return this.voyagesForLieIdLieu;
    }

    public void setVoyagesForLieIdLieu(Set<Voyage> voyagesForLieIdLieu) {
        this.voyagesForLieIdLieu = voyagesForLieIdLieu;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "lieuArrive")
    public Set<Voyage> getVoyagesForIdLieu() {
        return this.voyagesForIdLieu;
    }

    public void setVoyagesForIdLieu(Set<Voyage> voyagesForIdLieu) {
        this.voyagesForIdLieu = voyagesForIdLieu;
    }

}

TripController.java

@Controller

public class TripController {

    @Autowired
    VoyageService voyageService;
    @Autowired
    LieuService lieuService;
    @Autowired
    MoyenDeTransportService moyenDeTransportService;

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        dateFormat.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class, "publishDate", new CustomDateEditor(dateFormat, false));

    }

    @RequestMapping(value = { "/addTrip" }, method = RequestMethod.GET)
    public String addTrip(ModelMap model) {
        Voyage voyage = new Voyage();

        model.addAttribute("voyage", voyage);

        return "addTrip";
    }

    @RequestMapping(value = { "/addTrip" }, method = RequestMethod.POST)
    public String saveTrip(ModelMap model, @ModelAttribute("voyage") Voyage voyage, BindingResult result) {

        voyageService.saveVoyage(voyage);

        return "addTrip";

    }

    @RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
    public String gethome(ModelMap model) {

        return "index";
    }

    @ModelAttribute("lieu")
    public List<Lieu> initializelieux() {
        return lieuService.allLieu();
    }

    @ModelAttribute("moyenDeTransports")
    public List<Moyendetransport> initializeMoyenDeTransport() {
        return moyenDeTransportService.allMoyenDeTransport();
    }
}

addTrip.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">




</head>

<body>

    <h2>addTrip Form</h2>

    <form:form modelAttribute="voyage" method="POST" acceptCharset="UTF-8">
        <form:input type="hidden" path="idVoyage" id="id" />



        <table>

            <tr>
                <td><label for="depart">date de depart </label></td>
                <td><form:input type ="date" path="depart" id="depart" /></td>
            </tr>

            <tr>
                <td><label for="arrivee">date d'arrivée: </label></td>
                <td><form:input path="arrivee" id="arrivee" /></td>

            </tr>



            <tr>
                <td><label for="moyendetransport">Moyen de transport </label></td>
                <td><form:select path="moyendetransport">
                        <form:options items="${moyenDeTransports}"
                            itemValue="libelleMoyendetransport" itemLabel="libelleMoyendetransport" />
                    </form:select></td>

            </tr>

            <tr>
                <td><label for="lieuArrive">Lieu de départ </label></td>
                <td><form:select path="lieuArrive">
                        <form:options items="${lieu}" itemValue="idLieu"
                            itemLabel="pays" />
                    </form:select></td>

            </tr>
            <tr>
                <td><label for="lieuDepart">Lieu d'arrivé </label></td>
                <td><form:select path="lieuDepart">
                        <form:options items="${lieu}" itemValue="idLieu"
                            itemLabel="pays" />
                    </form:select></td>

            </tr>

            <tr>
                <td colspan="3"><c:choose>
                        <c:when test="${edit}">
                            <input type="submit" value="Update" />
                        </c:when>
                        <c:otherwise>
                            <input type="submit" value="Register" />
                        </c:otherwise>
                    </c:choose></td>
            </tr>
        </table>
    </form:form>
    <br />

</body>
</html>

Erros:

GRAVE: Servlet.service() for servlet [dispatcher] in context with path [/Voyage] threw exception [Request processing failed; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'ID_LIEU' cannot be null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
    at com.mysql.jdbc.Util.getInstance(Util.java:383)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1049)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2840)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
    at com.oneway.voyage.dao.AbstractDao.persist(AbstractDao.java:34)
    at com.oneway.voyage.dao.VoyageDaoImp.saveVoyage(VoyageDaoImp.java:18)
    at com.oneway.voyage.service.VoyageServiceImp.saveVoyage(VoyageServiceImp.java:22)
    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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy38.saveVoyage(Unknown Source)
    at com.oneway.voyage.controller.TripController.saveTrip(TripController.java:57)
    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:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
    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)

2 个答案:

答案 0 :(得分:0)

您在Voyage实体中指定带有$ sudo ln -s /path/to/java-cef/src/third_party/cef/linux64/Resources/icudtl.dat /usr/lib/jvm/java-8-oracle/bin/icudtl.dat $ sudo ln -s /path/to/java-cef/src/third_party/cef/linux64/Debug/natives_blob.bin /usr/lib/jvm/java-8-oracle/bin/natives_blob.bin $ sudo ln -s /path/to/java-cef/src/third_party/cef/linux64/Debug/snapshot_blob.bin /usr/lib/jvm/java-8-oracle/bin/snapshot_blob.bin 的LIEU_ARRIVE FK列。你肯定会尝试插入一个没有Lieu d'arrivé的航程(一种没有目的地的航程: - )

答案 1 :(得分:0)

看起来您的lieuArrive属性未被保留。如果您希望将其与父级一起保存,则需要添加CascadeType

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_LIEU", nullable = false, cascade = CascadeType.ALL)
public Lieu getlieuArrive() {
    return this.lieuArrive;
}

然后它将被保存(和删除)以及您的父实体。如果您不需要更新,则只能使用CascadeType.PERSIST