使用hibernate检索视图中的数据** ManyToOne **单向映射

时间:2017-05-11 19:36:47

标签: java hibernate spring-mvc

我第一次尝试使用hibernate多对一单向映射。

   create table CGroup_1(GID  number(10) NOT NULL,
                          DATECREATED date,
                          EMAILADDRESS VARCHAR2(255),
                          GNAME VARCHAR2(255),PRIMARY KEY(GID));

    create table EMP_TBL_1 (
    eid number(10) not null,
    account_locked number(1),
    createdDate date,
    email varchar2(255),
    enabled number(1),
    expiryDate date,
    firstName varchar2(255),
    lastNmae varchar2(255),
    pwd varchar2(255),
    postCode varchar2(255),
    groupId number(10),
    PRIMARY KEY(eid));

    ALTER TABLE EMP_TBL_1
    ADD FOREIGN KEY (groupId) REFERENCES CGroup_1(GID);

Employee.java

  @Entity
  @Table(name="EMP_TBL_1")
  public class Employee implements Serializable {

    private static final long serialVersionUID=47L;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int eid;

    @Column
    private String firstName;
    @Column
    private String lastNmae;

    @Column
    private String email;
    @Column
    private String pwd;
    @Column
    private boolean account_locked;
    @Column
    private boolean enabled;
    @Column
    private Date createdDate;
    @Column
    private Date expiryDate;
    @Column
    private String postCode;
    @Column
    private CorporateGroup group;
    @Column
    private int gid;

    @ManyToOne(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
    @JoinColumn(name = "gid",referencedColumnName="gid")
    public CorporateGroup getGroup() {
    return group;
    }
    public void setGroup(CorporateGroup group) {
    this.group = group;
    }
    //getters and setters
}

CorporateGroup.java:

@Entity
@Table(name="CGroup_1")
public class CorporateGroup implements Serializable {
    private static final long serialVersionUID=17L;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int gid;

    @Column
    private String gname;

    @Column
    private String emailAddress;

    @Column
    private Date dateCreated;

    //getters and setters
}

EmployeeDAOImpl.java

@Repository
public class EmployeeDAOImpl implements EmployeeDAO {
    @Autowired
    private SessionFactory sessionFactory;
    public void addEmployee(Employee emp) {
        sessionFactory.getCurrentSession().saveOrUpdate(emp);

    }

    @SuppressWarnings("unchecked")
    public List<Employee> getGroupEmployees(CorporateGroup group) {

        return sessionFactory.getCurrentSession().createQuery("from  Employee emp  
    where emp.gid=?").setInteger(0,group.getId()).list();

    }
}

CorporateGroupDAOImpl.java

@Repository
public class CorporateGroupDAOImpl implements CorporateGroupDAO{
    @Autowired
    private SessionFactory sessionFactory;
    public void addGroup(CorporateGroup group) {
        sessionFactory.getCurrentSession().saveOrUpdate(group);

    }

    @SuppressWarnings("unchecked")
    public List<CorporateGroup> getAllGroups() {

        return sessionFactory.getCurrentSession().createQuery("from 
CorporateGroup")
            .list();
    }

    public CorporateGroup getGroup(int id) {
        return (CorporateGroup) 
     sessionFactory.getCurrentSession().get(CorporateGroup.class,id);
    }
}

当我尝试在getGroupEmployees(CorporateGroup group)课程中调用EmployeeDAOImpl时,我收到以下错误

堆栈跟踪

 HTTP Status 500 - Request processing failed; nested exception is 
 org.hibernate.exception.SQLGrammarException: could not extract ResultSet

 type Exception report

 message Request processing failed; nested exception is 
 org.hibernate.exception.SQLGrammarException: could not extract ResultSet

 description The server encountered an internal error that prevented it from 
 fulfilling this request.

 exception

 org.springframework.web.util.NestedServletException: Request processing 
 failed; nested exception is org.hibernate.exception.SQLGrammarException: 
 could not extract ResultSet
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)

 org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
root cause

org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:89)
org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
org.hibernate.loader.Loader.doQuery(Loader.java:909)
org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
org.hibernate.loader.Loader.doList(Loader.java:2553)
org.hibernate.loader.Loader.doList(Loader.java:2539)
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
org.hibernate.loader.Loader.list(Loader.java:2364)
org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
com.myproject.DAO.EmployeeDAOImpl.getGroupEmployees(EmployeeDAOImpl.java:51)
com.myproject.service.EmployeeServiceImpl.getGroupEmployees(EmployeeServiceImpl.java:48)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy379.getGroupEmployees(Unknown Source)
com.myproject.controller.CorporateGroupController.listEmployees(CorporateGroupController.java:55)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
root cause

java.sql.SQLSyntaxErrorException: ORA-01747: invalid user.table.column, 
table.column, or column specification

oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:886)
oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1175)
oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1296)
oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3657)
oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1495)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
org.hibernate.loader.Loader.doQuery(Loader.java:909)
org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
org.hibernate.loader.Loader.doList(Loader.java:2553)
org.hibernate.loader.Loader.doList(Loader.java:2539)
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
org.hibernate.loader.Loader.list(Loader.java:2364)
org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
com.myproject.DAO.EmployeeDAOImpl.getGroupEmployees(EmployeeDAOImpl.java:51)
com.myproject.service.EmployeeServiceImpl.getGroupEmployees(EmployeeServiceImpl.java:48)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy379.getGroupEmployees(Unknown Source)
com.myproject.controller.CorporateGroupController.listEmployees(CorporateGroupController.java:55)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

启用后,hibernate.show_sql = true

我可以在控制台中看到以下内容:

   Hibernate: 
   select
    corporateg0_.gid as gid1_0_0_,
    corporateg0_.dateCreated as dateCreated2_0_0_,
    corporateg0_.emailAddress as emailAddress3_0_0_,
    corporateg0_.gname as gname4_0_0_ 
    from
    CGroup_1 corporateg0_ 
    where
    corporateg0_.gid=?

    Hibernate: 
    select
    employee0_.eid as eid1_1_,
    employee0_.account_locked as account_locked2_1_,
    employee0_.createdDate as createdDate3_1_,
    employee0_.email as email4_1_,
    employee0_.enabled as enabled5_1_,
    employee0_.expiryDate as expiryDate6_1_,
    employee0_.firstName as firstName7_1_,
    employee0_.gid as gid8_1_,
    employee0_.group as group9_1_,
    employee0_.lastNmae as lastNmae10_1_,
    employee0_.postCode as postCode11_1_,
    employee0_.pwd as pwd12_1_ 

    from

    EMP_TBL_1 employee0_ 
    where
    employee0_.gid=?

1 个答案:

答案 0 :(得分:0)

我的建议:

一,尝试不在字段和访问方法之间混合使用JPA注释(选择一个并坚持使用)...所以尝试将@ManyToOne注释从访问方法传递到字段group ...

二,员工表中没有列"gid" ...要映射的列是"groupId" ...所以删除字段:@Column private int gid;

并将@JoinColumn注释更正为:

@JoinColumn(name = "groupId", referencedColumnName = "gid")

希望这有帮助!