当前位置: 首页 > 知识库问答 >
问题:

无法在使用Hibernate的Spring MVC中获取多对多映射数据

宇文育
2023-03-14

参考此Hibernate文档后
在我的情况下,将“Person”替换为“Employee”,将“Phone”替换为“Company”,将“Person\u Phone”替换为“EmployeeCompany”。

以上Hibernate docs示例和my project示例的唯一区别是黑白。在Hibernate文档示例“Person\u Phone”中,将“phones\u Id”作为唯一约束。而在我的例子“EmployeeCompany”中,我将“employeeId”和“companyId”组合作为主键。

基本上,我有一个具有m: n关系的员工和公司表。这意味着一个员工可以在多个公司工作,一个公司可以有多个员工。

将此m:n关系解析为1:n关系。我创建了第三个表“EmployeeCompany”。

使用下面的get员工()函数,我想获取与员工关联的所有公司,因为我在员工表中使用了@OneTo众多注释。

public List<Employee> getEmployees() {
    Session session = this.sessionFactory.getCurrentSession();
    List<Employee> employees = session.createQuery("from Employee").list();
    return employees;
}

它在“Employee”类中抛出与“Companys”相关的异常。虽然从“Employee”类中删除“companies”字段效果很好,但我没有获得与该员工相关的公司数据。

员工模型类别:

@Entity
@Table(name = "employee")
public class Employee implements Serializable{
@Id
@GeneratedValue
@Column(name = "employeeId")
private Long employeeId;

@Column(columnDefinition = "text not null")
private String name;

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Company> companies = new ArrayList<Company>();

public Long getEmployeeId() {
    return employeeId;
}

public void setEmployeeId(Long employeeId) {
    this.articleId = articleId;
}

public String getName() {
    return heading;
}

public void setName(String name) {
    this.name = name;
}

public List<Company> getCompanies() {
    return companies;
}

public void setCompanies(List<Company> companies) {
    this.companies = companies;
}
}

EmployeeCompany模型类别:

@Entity
@Table(name = "employee_company")
public class EmployeeCompany implements Serializable {

    @EmbeddedId
    private EmployeeCompanyKey key;

    public EmployeeCompanyKey getKey() {
        return key;
    }

    public void setKey(EmployeeCompanyKey key) {
        this.key = key;
    }
}

EmployeeCompanyKey类别:

@Embeddable
public class EmployeeCompanyKey implements Serializable{
    @Column(name = "companyId",columnDefinition = "varchar(100) not null")
    private String companyId;

    @Column(name = "employeeId",columnDefinition = "bigint(20) unsigned not null")
    private Long employeeId;


    public String getCompanyId() {
        return companyId;
    }

    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }

    public Long getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(Long employeeId) {
        this.employeeId = employeeId;
    }


    public int hashCode(){
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((companyId == null) ? 0 : companyId.hashCode());
        result = prime * result + employeeId.hashCode();
        return result;
    }


    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        EmployeeCompanyKey other = (EmployeeCompanyKey) obj;
        if (companyId == null) {
            if (other.companyId != null)
                return false;
        } else if (!companyId.equals(other.companyId)){
            return false;
        }
        if (employeeId != other.employeeId)
            return false;
        return true;
    }

}

公司模型类:

@Entity
@Table(name = "company")
public class Company implements Serializable{

    @Id
    @Column(name = "companyId",columnDefinition = "varchar(100) not null")
    private String companyId;

    @Column(name = "name",columnDefinition = "text not null")
    private String name;

    public String getCompanyId() {
        return companyId;
    }

    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

这是我的SQL查询使DB:

DROP TABLE IF EXISTS `employee`;
CREATE TABLE employee (
`employeeId` bigint(20) unsigned not null auto_increment,
`name` text not null,
primary key(`employeeId`)
)ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;   

DROP TABLE IF EXISTS `employee_company`;
CREATE TABLE employee_company (
`employeeId` bigint(20) unsigned not null,
`companyId` varchar(100) not null,
primary key(`employeeId`,`companyId`),
CONSTRAINT `company_employee_company_fk` FOREIGN KEY (`companyId`) REFERENCES `company`(`companyId`) ON DELETE CASCADE,
CONSTRAINT `employee_employee_company_fk` FOREIGN KEY (`employeeId`) REFERENCES `employee`(`employeeId`) ON DELETE CASCADE
)ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;   


DROP TABLE IF EXISTS `company`;
CREATE TABLE company (
`companyId` varchar(100) not null,
`name` text not null,
primary key(`companyId`)
)ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

请解释我哪里做错了?如果我想要公司数据和所有员工数据,我该怎么办?

编辑1:这是我的邮递员响应输出:

    <body>
        <h1>HTTP Status 500 - Could not write content: failed to lazily initialize a collection of role: com.argnv.myproject.Models.Employee.companies, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]-&gt;com.argnv.myproject.Models.Employee[&quot;companies&quot;]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.argnv.myproject.Models.Employee.companies, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]-&gt;com.argnv.myproject.Models.Employee[&quot;companies&quot;])</h1>
        <HR size="1" noshade="noshade">
        <p>
            <b>type</b> Exception report
        </p>
        <p>
            <b>message</b>
            <u>Could not write content: failed to lazily initialize a collection of role: com.argnv.myproject.Models.Employee.companies, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]-&gt;com.argnv.myproject.Models.Employee[&quot;companies&quot;]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.argnv.myproject.Models.Employee.companies, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]-&gt;com.argnv.myproject.Models.Employee[&quot;companies&quot;])</u>
        </p>
        <p>
            <b>description</b>
            <u>The server encountered an internal error that prevented it from fulfilling this request.</u>
        </p>
        <p>
            <b>exception</b>
            <pre>org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: failed to lazily initialize a collection of role: com.argnv.myproject.Models.Employee.companies, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]-&gt;com.argnv.myproject.Models.Employee[&quot;companies&quot;]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.argnv.myproject.Models.Employee.companies, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]-&gt;com.argnv.myproject.Models.Employee[&quot;companies&quot;])
    org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:238)
    org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:101)
    org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:167)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    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:966)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</pre>
        </p>
        <p>
            <b>root cause</b>
            <pre>com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.argnv.myproject.Models.Employee.companies, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]-&gt;com.argnv.myproject.Models.Employee[&quot;companies&quot;])
    com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
    com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
    com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:184)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:605)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
    com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
    com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
    com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:118)
    com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1819)
    org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
    org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:101)
    org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:167)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    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:966)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</pre>
        </p>
        <p>
            <b>root cause</b>
            <pre>org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.argnv.myproject.Models.Employee.companies, could not initialize proxy - no Session
    org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
    org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
    org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
    org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)
    org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:266)
    com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:90)
    com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
    com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
    com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
    com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
    com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:118)
    com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1819)
    org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
    org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:101)
    org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:167)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    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:966)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</pre>
        </p>
        <p>
            <b>note</b>
            <u>The full stack trace of the root cause is available in the Apache Tomcat/7.0.53 logs.</u>
        </p>
        <HR size="1" noshade="noshade">
        <h3>Apache Tomcat/7.0.53</h3>
    </body>

共有1个答案

裴哲
2023-03-14

公司ey.class

@Embeddable
public class EmployeeCompanyKey implements Serializable{
@Column(name = "companyId",columnDefinition = "varchar(100) not null")
private String companyId;

@Column(name = "companyId",columnDefinition = "bigint(20) unsigned not null")
private Long employeeId;

改变

 @Column(name = "companyId",columnDefinition = "bigint(20) unsigned not null")
private Long employeeId;

@Column(name = "employeeId",columnDefinition = "bigint(20) unsigned not null") private Long employeeId;

然后再试一次?

 类似资料:
  • 您好,我有多对多映射,在联接表中有额外的列。表结构如下所示。 关系如下 链接 我创建了如下POJO类 Vendor.java 学生。爪哇 测试。爪哇 供应商est.java 供应商学生测试PK。爪哇 Hibernate映射文件,如下所示 vendor.hbm.xml vendor\u student\u测试。hbm。xml 大学生hbm。xml 测验hbm。xml 我刚开始Hibernate,这是

  • 下面的映射给出的错误为 从db.karateInvoiceDetail引用db.karateInvoice的外键的列数错误。应为1 想法是有一个表,它的组合键为(id、fiscalyear和companyId),而表的组合键为(seqNo、InvoiceId、InvoiceFiscalYear和InvoiceCompanyId)。

  • 1. 前言 本节课,咱们一起继续聊聊多对多关联映射。通过本节课程,你将了解到: 多对多关联映射的实现; 双向多对多关联映射的实现。 2. 多对多关联映射 首先了解表中的多对多关系,学生表中的数据和课程表中的数据就存在多对多关系。 一名学生可以选修多门课程,一门课程可以供多名学生选修。 数据库通过主外键的机制描述表中的数据之间的关系。对于存在多对多关系的数据表,借助于中间表,分拆成两个一对多(或者多

  • 我已经尝试了表2的hibernate映射: 上面不起作用。在获取记录时,它试图从表2中获取表1中根本不存在的LOB代码

  • 问题内容: 我正在开发一个处理以下两个实体的应用程序: 产品 (将其命名为X,Y,Z)和 材料 (a,b,c,…)。众所周知,每种产品都有一个配方,指示制造该产品所需的材料。例如,要产生一个X,我们需要2 a,6 c和4 d(X = 2a + 6c + 4d)。 这就是它在数据库表中的反映方式: 第三张表中的“计数”字段是同类材料(本例中为2、6、4)的系数。 所以我想以这种方式编写Product

  • 我想使用XML映射在Hibernate中映射多对多的关系。 我有两个类,和。我想创建一个链接表女巫将包含复合键和3个额外的列