简体   繁体   中英

jpa/hibernate one-to-one mapping

        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;
        }

    }

ERROR

 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)

I am trying to achieve one-to-one relationship unidirectional using foreign key in the associated table. While inserting the date, it is inserting the data in the primary key table but is giving error to insert above error.

You are using a primary key as a join column.

In a @OneToOne , the joinColumn is a column that references the other side of the relationship. Since id is the primary key column, you shouldn't use that as a foreign key column as well (it's the name of the referencing column, not the referenced column).

Change joinColumn to something like emp_id (or remove it all together to get the default value.)

The exception is probably caused by the way Hibernate persists relationships, usually it first inserts both sides of the relationship, and the does an update to create the relationship. Here, this update will be on a primary key column, which fails.

Even though the 2 tables will hold the same value of a primary key ie employee id, it cannot be inserted through the above code. I will suggest to use the below way to achieve this.

select person-primarykey.nextVal from dual;

This will give you the next value of the sequence and then make 2 transactions to insert in both the tables passing the generated value as the id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM