在调用save()之前必须手动分配此类的ID:com.javaknowledge.entity.Motor

时间:2015-08-05 01:11:43

标签: java xml hibernate

我想在hibernate中进行一对多的映射。我已经按照一些教程但仍然在id中出错,实际上我的项目中的“id”是“STRING” 以下是我的代码

Motor.java

package com.javaknowledge.entity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.model.UploadedFile;
import java.sql.Blob;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Id;
/**
 *
 * @author VENNY
*/
@ManagedBean
@SessionScoped

public class Motor implements java.io.Serializable{
    @Id
    private String VFRAMENUM;    
    private Customer customer;
    private String VENGINENUM;
    private String VNOPOL;
    private String VTYPECODE;
    private String VCLRCODE;
    private int VTHNPROD;
    private int NKMSERVICE;


    public Motor(){

    }

    public Customer getCustomer() {
        return customer;
    }
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
//setter getter        
}

Customer.java

package com.javaknowledge.entity;
/**
 *
 * @author VENNY
*/
@ManagedBean
@SessionScoped
public class Customer implements java.io.Serializable {
    @Id
    private String VIDPROSPEK;
    private String VNAME;
    private String VADRESS;   
    private String NPHONENUM;
    private String hubunganPM;
    private String sd, msg, selectedVCLRDESC;

    private Set motors = new HashSet(0);

    public Customer() {

    }

    public Customer(String VIDPROSPEK, String VNAME, String VADRESS, String NPHONENUM, String hubunganPM) {
        this.VIDPROSPEK = VIDPROSPEK;
        this.VNAME = VNAME;
        this.VADRESS = VADRESS;        
        this.NPHONENUM = NPHONENUM;
        this.hubunganPM = hubunganPM;
    }

    public Set getMotors() {
        return motors;
    }

    public void setMotors(Set motors) {
        this.motors = motors;
    }
//setter getter
}

CustomerDao.java

public class CustomerDao {

    public void addCustomer(Customer cust) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            cust.getVIDPROSPEK();
            cust.getNPHONENUM();
            cust.getVADRESS();
            cust.getVNAME();
            cust.getHubunganPM();
            session.save(cust);

            Motor motid = new Motor();
            motid.getVFRAMENUM();
            motid.getVENGINENUM();
            motid.getVNOPOL();
            motid.getVTYPECODE();
            motid.getVTHNPROD();
            motid.getNKMSERVICE();

            motid.setCustomer(cust);
            cust.getMotors().add(motid);
            session.save(motid);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }
}

Customer.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jul 5, 2013 10:57:32 AM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="com.javaknowledge.entity.Customer" table="ahmdsmun_mstprospek" catalog="ahmids">
        <id name="VIDPROSPEK" type="string">
            <column name="VIDPROSPEK" />
            <generator class="assigned"></generator>
        </id>
        <property name="VNAME" type="string">
            <column name="VNAME" length="100" not-null="true" />
        </property>
        <property name="VADRESS" type="string">
            <column name="VADRESS" length="100" not-null="true" />
        </property>
        <property name="NPHONENUM" type="string">
            <column name="NPHONENUM" length="15" />
        </property>
        <property name="hubunganPM" type="string">
            <column name="hubunganPM" length="4"/>
        </property>
        <set name="motors" table="ahmdsmts_mstmotor" 
                inverse="true" lazy="true" fetch="select">
            <key>
                <column name="VIDCUSTOMER" not-null="true" />
            </key>
            <one-to-many class="com.javaknowledge.entity.Motor" />
        </set>
    </class>
</hibernate-mapping>

Motor.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jul 5, 2013 10:57:32 AM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="com.javaknowledge.entity.Motor" table="ahmdsmts_mstmotor" catalog="ahmids">
        <id name="VFRAMENUM" type="string">
            <column name="VFRAMENUM" />
            <generator class="assigned"></generator>
        </id>
        <many-to-one name="customer" class="com.javaknowledge.entity.Customer" fetch="select">
            <column name="VIDPROSPEK" not-null="true" />
        </many-to-one>
        <property name="VENGINENUM" type="string">
            <column name="VENGINENUM" length="100" not-null="true" />
        </property>
        <property name="VNOPOL" type="string">
            <column name="VNOPOL" length="100" not-null="true" />
        </property>
        <property name="VTYPECODE" type="string">
            <column name="VTYPECODE" length="15" />
        </property>
        <property name="VCLRCODE" type="string">
            <column name="VCLRCODE" length="4"/>
        </property>
        <property name="VTHNPROD" type="int">
            <column name="VTHNPROD" length="100" />
        </property> 
        <property name="NKMSERVICE" type="int">
            <column name="NKMSERVICE" length="100" />
        </property>

    </class>
</hibernate-mapping>

我认为这一切都需要知道。我在.hbm.xml中做错了吗?

请注意: - 在客户表中,VIDPROSPEK(String)是PK - 在电机表中,VFRAMENUM(字符串)是PK,VIDCUSTOMER是带VIDPROSPEK的FK

这是stacktrace:

Info:   WebApplication1_1_test was successfully deployed in 4,056 milliseconds.
Info:   WebModule[null] ServletContext.log():Destroying Spring FrameworkServlet 'dispatcher'
Info:   Closing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Wed Aug 05 09:12:11 SGT 2015]; parent: Root WebApplicationContext
Info:   WebModule[null] ServletContext.log():Closing Spring root WebApplicationContext
Info:   Closing Root WebApplicationContext: startup date [Wed Aug 05 09:12:10 SGT 2015]; root of context hierarchy
Warning:   The web application [/saveDatabaseTabCustomer_retrieveTabServicePart] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   WebModule[null] ServletContext.log():No Spring WebApplicationInitializer types detected on classpath
Info:   Registering WebSocket filter for url pattern /*
Info:   Initializing Mojarra 2.2.7 ( 20140610-1547 https://svn.java.net/svn/mojarra~svn/tags/2.2.7@13362) for context '/saveDatabaseTabCustomer_retrieveTabServicePart'
Info:   Monitoring jndi:/server/saveDatabaseTabCustomer_retrieveTabServicePart/WEB-INF/faces-config.xml for modifications
Info:   Running on PrimeFaces 3.5
Info:   WebModule[null] ServletContext.log():Initializing Spring root WebApplicationContext
Info:   Root WebApplicationContext: initialization started
Info:   Refreshing Root WebApplicationContext: startup date [Wed Aug 05 09:26:26 SGT 2015]; root of context hierarchy
Info:   Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
Info:   Loaded JDBC driver: com.mysql.jdbc.Driver
Info:   Root WebApplicationContext: initialization completed in 466 ms
Info:   WebModule[null] ServletContext.log():Initializing Spring FrameworkServlet 'dispatcher'
Info:   FrameworkServlet 'dispatcher': initialization started
Info:   Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Wed Aug 05 09:26:26 SGT 2015]; parent: Root WebApplicationContext
Info:   Loading XML bean definitions from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
Info:   Mapped URL path [/index.htm] onto handler 'indexController'
Info:   FrameworkServlet 'dispatcher': initialization completed in 205 ms
Info:   Loading application [WebApplication1_1_test] at [/saveDatabaseTabCustomer_retrieveTabServicePart]
Info:   WebApplication1_1_test was successfully deployed in 3,132 milliseconds.
Info:   HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Info:   HHH000412: Hibernate Core {4.3.1.Final}
Info:   HHH000206: hibernate.properties not found
Info:   HHH000021: Bytecode provider name : javassist
Info:   HHH000043: Configuring from resource: /hibernate.cfg.xml
Info:   HHH000040: Configuration resource: /hibernate.cfg.xml
WARN:   HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Info:   HHH000221: Reading mappings from resource: com/javaknowledge/entity/Customer.hbm.xml
WARN:   HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Info:   HHH000221: Reading mappings from resource: com/javaknowledge/entity/TipeMotor.hbm.xml
WARN:   HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Info:   HHH000221: Reading mappings from resource: com/javaknowledge/entity/Service.hbm.xml
WARN:   HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Info:   HHH000221: Reading mappings from resource: com/javaknowledge/entity/Motor.hbm.xml
WARN:   HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Info:   HHH000041: Configured SessionFactory: null
WARN:   HHH000402: Using Hibernate built-in connection pool (not for production use!)
Info:   HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/ahmids?zeroDateTimeBehavior=convertToNull]
Info:   HHH000046: Connection properties: {user=root, password=****}
Info:   HHH000006: Autocommit mode: false
Info:   HHH000115: Hibernate connection pool size: 20 (min=1)
Info:   HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Info:   HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Info:   HHH000399: Using default transaction strategy (direct JDBC transactions)
Info:   HHH000397: Using ASTQueryTranslatorFactory
Severe:   org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.javaknowledge.entity.Motor
    at org.hibernate.id.Assigned.generate(Assigned.java:52)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:711)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:703)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:698)
    at com.javaknowledge.dao.CustomerDao.addCustomer(CustomerDao.java:42)
    at com.javaknowledge.entity.Customer.saveCustomer(Customer.java:116)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:295)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)

0 个答案:

没有答案