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

Hibernate:OneToMany映射失败

潘星阑
2023-03-14

我刚开始冬眠,尝试一些应该很容易的事情,但我无法让它工作。

有两个表,一个人和一个地址。一个人可以有一个或多个地址,即:一个OneTo多映射。当我试图向两个不同的人添加相同的地址时,我会遇到异常。这几乎就像Unique在连接表的foriegn_key上被强制执行一样。

我的源代码:

package testing.com.hibernate.entities;

import java.util.HashSet;
import html" target="_blank">java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="Person")
public class Person {
private long personID; 
private String personName;
private Set<Address> addresses = new HashSet<Address>(0);

public Person() {}

public Person(String personName, Set<Address> addresses) {
    setPersonName(personName);
    setAddresses(addresses);
}

@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy="increment")
@Column(name="Person_ID")
public long getPersonID() {
    return personID;
}
@Column(name="Person_Name")
public String getPersonName() {
    return personName;
}
@OneToMany
@JoinTable(name = "PersonAddresses", joinColumns = {@JoinColumn(name="PersonID", unique=false)}, inverseJoinColumns = {@JoinColumn(name="AddressID", unique=false)})
public Set<Address> getAddresses() {
    return addresses;
}

public void setPersonID(long personID) {
    this.personID = personID;
}
public void setPersonName(String personName) {
    this.personName = personName;
}
public void setAddresses(Set<Address> addresses) {
    this.addresses = addresses;
}
}

地址

package testing.com.hibernate.entities;

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

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="Address")
public class Address {
private long addressID;
private String address; 

public Address() {}

public Address(String address) {
    setAddress(address);
}

@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy="increment")
@Column(name="Address_ID")
public long getAddressID() {
    return addressID;
}
@Column(name="Address")
public String getAddress() {
    return address;
}

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

主要

package testing.com.hibernate.tests;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import testing.com.hibernate.entities.Address;
import testing.com.hibernate.entities.EntityCategory;
import testing.com.hibernate.entities.EntityNetflixFilm;
import testing.com.hibernate.entities.Person;
import testing.com.hibernate.sessionmanager.HibernateUtil;

import org.hibernate.Session;

public class Test {

public static void main(String[] args) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    // Create multiple addresses
    Address addr1 = new Address("Address one");
    Address addr2 = new Address("Address two");
    Address addr3 = new Address("Address three");
    Address addr4 = new Address("Address four");

    // Add all addresses to the database
    session.beginTransaction();
    session.save(addr1);
    session.save(addr2);
    session.save(addr3);
    session.save(addr4);
    session.getTransaction().commit();
    session.close();

    /*
     * At this point in the code there will be four addresses 
     * in the table 'Address'. 
     * 
     * 1 - Address one
     * 2 - Address two
     * 3 - Address three
     * 4 - Address four
     * 
     * Now we want to create some people and add addresses to them
     */

    // Pull out a list of addresses from the database
    List<Address> addresses = null;
    session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    addresses = session.createQuery("from Address").list();
    session.getTransaction().commit();
    session.close();

    /*
     * We now have a List of Address objects.
     * 
     * This is replicating a Database with existing
     * Addresses and querying them from the table
     * to attach to a new Person being added. 
     */

    // Create person with Address 1 and 2
    Set<Address> addressSet1 = new HashSet<Address>();
    addressSet1.add(addresses.get(0));
    addressSet1.add(addresses.get(1));
    Person george = new Person("George", addressSet1);

    // Create person with Address 3 and 4
    Set<Address> addressSet2 = new HashSet<Address>();
    addressSet2.add(addresses.get(2));
    addressSet2.add(addresses.get(3));
    Person robert = new Person("Robert", addressSet2);

    // Create person with Address 1 and 2. The same as George
    Person harry = new Person("Harry", addressSet1);

    // Attempt to add them to the Person table
    session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    session.save(george);
    session.save(robert);
    session.save(harry);
    session.getTransaction().commit();
    session.close();
}
}

代码在保存Person对象Harry时崩溃。这是因为在个人地址表中,引用“1”的地址已经存在并分配给“乔治”。我怎样才能让哈利和乔治映射到地址1?

日志

Hibernate:插入Person(Person_Name,Person_ID)值 (?, ?)22:39:42,284TRACE BasicBinder:83-绑定参数[1]为[VARCHAR]-George22:39:42,284TRACE BasicBinder:83-绑定参数[2]为[BIGINT]-1 Hibernate:插入到Person(Person_Name,Person_ID)值 (?, ?)22:39:42,285TRACE BasicBinder:83-绑定参数[1]为[VARCHAR]-Robert22:39:42,286TRACE BasicBinder:83-绑定参数[2]为[BIGINT]-2 Hibernate:插入到Person(Person_Name,Person_ID)值 (?, ?)22:39:42,287TRACE BasicBinder:83-绑定参数[1]为[VARCHAR]-Harry22:39:42,287TRACE BasicBinder:83-绑定参数[2]为[BIGINT]-3

Hibernate:在PersonalAddresses(PersonID,AddressID)中插入值(?,)22:39:42289 TRACE BasicBinder:83-将参数[1]绑定为[BIGINT]-1 22:39:42292 TRACE BasicBinder:83-将参数[2]绑定为[BIGINT]-1

Hibernate:在PersonalAddresses(PersonID,AddressID)中插入值(?,)22:39:42294 TRACE BasicBinder:83-绑定参数[1]为[BIGINT]-1 22:39:42295 TRACE BasicBinder:83-绑定参数[2]为[BIGINT]-2

Hibernate:插入到个人地址(个人ID,地址)值 (?, ?)22:39:42,296TRACE BasicBinder: 83-绑定参数[1]作为[BIGINT]- 2 22:39:42,296TRACE BasicBinder: 83-绑定参数[2]作为[BIGINT]-3

Hibernate:在PersonalAddresses(PersonID,AddressID)中插入值(?,)22:39:42297 TRACE BasicBinder:83-将参数[1]绑定为[BIGINT]-2 22:39:42298 TRACE BasicBinder:83-将参数[2]绑定为[BIGINT]-4

Hibernate:在PersonalAddresses(PersonID,AddressID)中插入值(?,)22:39:42298 TRACE BasicBinder:83-将参数[1]绑定为[BIGINT]-3 22:39:42300 TRACE BasicBinder:83-将参数[2]绑定为[BIGINT]-1

22:39:42320警告SqlExceptionHelper:143-SQL错误:1062,SQLState:23000 22:39:42320错误SqlExceptionHelper:144-键“AddressID”的重复条目“1”

线程“main”组织中出现异常。冬眠例外ConstraintViolationException:键“AddressID”的重复条目“1”

共有1个答案

宋华灿
2023-03-14

好啊所以我自己解决了这个问题。

事实证明,Hibernate将一对多的“多”部分视为联接表中唯一的实体。这方面的一个例子是汽车/服务历史情况,您有一辆汽车记录其独特的服务历史。如果您尝试再次将维修历史记录添加到另一辆车,它将失败,因为此维修历史记录已经是一辆车所独有的。

如果你想共享信息,在这种情况下,一个可以在多人之间共享的地址,你需要一个多对多的关系。要修复此问题,请更新源代码,使此人拥有@ManyToMany并提供@JoinTable注释。

 类似资料:
  • 我在Spring启动时使用推土机映射器。如果我将数据从实体映射到EntityDTO,那么dozer maper的工作就是将数据从实体类复制到EntityDTO,对于原语也是如此。但是假设我有这样一门课 和名称为EntityDTO的DTO 那么它不会将数据从entityChild映射到EntityChildTos,有人能帮我解决这个问题吗?

  • 在scala中失败的最干净的方法是什么? 说我有: 如果未来以成功,我想保留它,但是如果它失败了,我想将更改为其他。 我能想出的最好的是转换,但是这需要我为成功案例做一个不必要的函数: 有什么原因没有< code > mapFailure(partial function[Throwable,Throwable])?

  • 我使用一个VanillaChroncile临时存储和检索条目,除了有巨大的负载外,它工作得非常好。我得到地图失败异常。虽然我有处理此异常的恢复逻辑,但我想知道为什么首先会出现此异常。任何帮助都将不胜感激。 }

  • 我正在使用Hibernate和JPA注释来映射我的类。当hibernate尝试映射这个类时,我遇到了一个问题 我的Social alStat类是: 我得到了这个错误: 我猜发生这种情况是因为我试图映射到一个基本类,但@ElementCollection注释不应该解决这个问题吗? 我的item类如下所示:

  • 前端将这个json发送到我的API 控制器: