jpa / hibernate一对一映射

时间:2014-11-11 12:34:45

标签: java hibernate jpa

        package com.sow.dao;

        import java.io.Serializable;

        import javax.persistence.CascadeType;
        import javax.persistence.Column;
        import javax.persistence.Entity;
        import javax.persistence.GeneratedValue;
        import javax.persistence.GenerationType;
        import javax.persistence.Id;
        import javax.persistence.JoinColumn;
        import javax.persistence.OneToOne;
        import javax.persistence.Table;
        import javax.xml.bind.annotation.XmlRootElement;

        @XmlRootElement
        @Entity
        @Table(name = "empcre")
        public class EmpAuth implements Serializable {
            @Id
            @GeneratedValue
            @Column(name = "id", unique = true, nullable = false)
            int id;
            @Column(name = "username")
            String userName;
            @Column(name = "userpwd")
            String Pwd;
            @OneToOne(mappedBy = "empcre")
            @JoinColumn(name = "id")
            private EmpDetails empDetails;

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public String getUserName() {
                return userName;
            }

            public void setUserName(String userName) {
                this.userName = userName;
            }

            public String getPwd() {
                return Pwd;
            }

            public void setPwd(String pwd) {
                Pwd = pwd;
            }

            public EmpDetails getEmpDetails() {
                return empDetails;
            }

            public void setEmpDetails(EmpDetails empDetails) {
                this.empDetails = empDetails;
            }

        }

            package com.sow.dao;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToOne;
    import javax.persistence.Table;

    import org.hibernate.annotations.GenericGenerator;
    import org.hibernate.annotations.Parameter;

    @Entity
    @Table(name = "empdetails")
    @GenericGenerator(name = "person-primarykey", strategy = "foreign", parameters = { @Parameter(name = "property", value = "empcre") })
    public class EmpDetails {
        @Id
        @GeneratedValue(generator = "person-primarykey")
        // @GenericGenerator(name = "gen", strategy = "foreign", parameters =
        // @Parameter(name = "property", value = "empcre"))
        @Column(name = "id", unique = true, nullable = false)
        int id;

        @Column(name = "empname")
        String empName;
        @Column(name = "address")
        String address;
        @Column(name = "empsal")
        String empSal;

        @OneToOne()
        @JoinColumn(name = "id")
        private EmpAuth empcre;

        public EmpAuth getEmpcre() {
            return empcre;
        }

        public void setEmpcre(EmpAuth empcre) {
            this.empcre = empcre;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getEmpName() {
            return empName;
        }

        public void setEmpName(String empName) {
            this.empName = empName;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public String getEmpSal() {
            return empSal;
        }

        public void setEmpSal(String empSal) {
            this.empSal = empSal;
        }

    }

错误

 SEVERE: Servlet.service() for servlet [jersey-serlvet] in context with path [/restDemo] threw exception
    org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.sow.dao.EmpDetails.empcre]
        at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:101)
        at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:120)
        at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:422)
        at org.hibernate.event.internal.DefaultMergeEventListener.mergeTransientEntity(DefaultMergeEventListener.java:342)
        at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:304)
        at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:259)
        at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:86)
        at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:781)
        at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:766)
        at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:770)
        at com.sow.UserService.newEmp(UserService.java:100)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
        at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
        at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
        at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
        at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
        at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
        at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:744)

我试图在关联表中使用外键实现单向一对一关系。在插入日期时,它会将数据插入主键表中,但是在插入上述错误时会出错。

2 个答案:

答案 0 :(得分:0)

您正在使用主键作为连接列。

@OneToOne中,joinColumn是引用关系另一面的列。由于id是主键列,因此您也不应将其用作外键列(它是引用列的名称,而不是引用列)。

joinColumn更改为emp_id之类的内容(或将其全部删除以获取默认值。)

异常可能是由Hibernate持久关系的方式引起的,通常它首先插入关系的两面,并进行更新以创建关系。此处,此更新将位于主键列上,该列失败。

答案 1 :(得分:0)

  

即使2个表将保持主键的相同值,即员工ID,也无法通过上述代码插入。   我建议使用以下方法来实现这一目标。

select person-primarykey.nextVal from dual;
  

这将为您提供序列的下一个值,然后在两个表中插入2个事务,并将生成的值作为id传递。