gpt4 book ai didi

java - Hibernate (JPA) - 无缘无故的奇怪更新

转载 作者:行者123 更新时间:2023-12-02 04:32:23 24 4
gpt4 key购买 nike

我有一个访问 oracle-db 的应用程序,该数据库将联系人存储在表中。创建、读取和更新工作正常。但删除有时会因为某些奇怪的原因而不起作用。

当我启动应用程序时,我从数据库加载所有当前联系人并将它们放入 javafx-table 中。我让 hibernate 向我展示它的所有 sql,这就是它在此之前所做的一切。它只做了一次选择。现在,如果我直接开始删除联系人,它对于 3-4 个联系人来说效果很好,然后我收到一个错误,告诉我,hibernate 尝试运行一个更新语句,其中它用作 id null。 Hibernate 为什么要这样做?

这完全是胡说八道。我对它进行了两次和三次检查,在 select 语句和删除之间没有运行任何数据库操作。为什么当我告诉 hibernate 删除时,它会毫无理由地进行更新?

在这里您可以看到了解我的情况可能需要的所有代码和信息

public void refresh() {
List<OrganisationContact> allContacts = EntityStore.ORGA_CON_REPO
.readAllWithDetails();
contactTable.getItems().setAll(allContacts);
}

这是我的存储库中的方法

    @Override
public List<OrganisationContact> readAllWithDetails() {
try {
JPAJinqStream<Contact> stream = getStreamForTable(Contact.class);
List<OrganisationContact> organisationContactList = new ArrayList<OrganisationContact>();
try {
stream.forEach(con -> organisationContactList
.add(new OrganisationContact(con)));
} catch (javax.persistence.PersistenceException exception) {
NoReplyFromDatabaseException.showErrorDialog();
throw new NoReplyFromDatabaseException(exception);
}
stream.close();
return organisationContactList;
} catch (javax.persistence.PersistenceException exception) {
NoReplyFromDatabaseException.showErrorDialog();
throw new NoReplyFromDatabaseException(exception);
}
}

这是我的抽象存储库中的方法,我的普通存储库正在使用

    protected <TableEntity>JPAJinqStream<TableEntity> getStreamForTable(final Class<TableEntity> pEntityClass) {
if (this.manager != null && this.factory != null && this.provider != null) {
if (this.manager.isOpen() && this.factory.isOpen()) {
return this.provider.streamAll(this.manager, pEntityClass);
}
}

return null;
}

manager 是 EntityMananger 的一个实例
工厂是EntityManagerFactory的一个实例
provider是JinqJPAStreamProvider的一个实例

这是删除联系人时执行的代码

    @FXML
public void onDelete() {

EntityStore.ORGA_CON_REPO.delete(EntityStore.CURRENT_CONTACT);
if (!UnitOfWork.closeTransaction(EntityStore.ORGA_CON_REPO, true)) {
// error occured
}

// ignore that stuff
EntityStore.CURRENT_CONTACT = null;
ModeManager.clearMode();
ModeManager.refreshTable();
}

ORGA_CON_REPO 是我上面的存储库
UnitOfWork 知道所有现有存储库(在本例中仅存在 1 个)并处理其事务

这是我的 UnitOfWork 类(class)

public final class UnitOfWork {

private static final Map<AbstractRepository<?>, EntityManager> units = new HashMap<AbstractRepository<?>, EntityManager>();

private UnitOfWork() {
}

/* PUBLIC */
/**
* Executes a commit/rollback and closes the transaction for the passed
* repository.
*
* @param pRepository
* The repository the transaction belongs to.
* @param pCommit
* If this parameter is <code>true</code>, the transaction will
* be commited before closing. If it is <code>false</code>, the
* transaction will be rolled back before closing.
* @return true if the transaction has been closed successfully, false if an error occured while closing or the manager was null
*/
public synchronized static boolean closeTransaction(
final AbstractRepository<?> pRepository, final boolean pCommit) {
EntityManager manager = units.get(pRepository);
if (manager != null) {
try {
EntityTransaction t = manager.getTransaction();
if (t.isActive()) {
if (pCommit) {
t.commit();
} else {
t.rollback();
}
}
units.remove(pRepository);

return true;
} catch (PersistenceException pException) {
pRepository.resetManager(false);
units.remove(pRepository);
// TODO: log and throw
}
}
return false;
}

/* PROTECTED */
/**
* Starts a new transaction in a new unit of work.
*
* @param pRepository
* The repository the transaction belongs to.
* @param pManager
* The EntityManager of the passed repository.
* @return <code>true</code> if the transaction has been started
* successfully, <code>false</code> if the manager is closed or one
* of the parameters is null.
*/
protected synchronized static boolean beginTransaction(
final AbstractRepository<?> pRepository,
final EntityManager pManager) {
if (pRepository != null || pManager != null) {
if (pManager.isOpen()) {
if (!units.containsKey(pRepository)) {
EntityTransaction t = pManager.getTransaction();
if (!t.isActive()) {
t.begin();
}
units.put(pRepository, pManager);
}
return true;
}
}
return false;
}

}

这是我的存储库的删除方法

    @Override
public boolean delete(OrganisationContact pEntity) {
Contact contactEntity = pEntity.getContact();
return remove(contactEntity);
}

它正在使用我的抽象存储库的方法

protected boolean remove(final Object pEntity) {
if (this.canManagerExecute(pEntity)) {
if (this.beginTransaction()) {
this.manager.remove(pEntity);
return true;
}
}
return false;
}

private boolean canManagerExecute(final Object pEntity) {
if (this.manager != null && pEntity != null) {
return this.manager.isOpen();
}
return false;
}

正在使用 hibernate 。
这是我的实体

@Entity
@Table(schema = "reskonverw")
public class Contact {
@Column(name = "phonenumber")
private String phoneNumber;
@Column(name = "firstname")
private String firstName;
@Column(name = "surname")
private String surname;
@Column(name = "email")
private String email;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name="id")
private int id;
@ManyToOne(cascade = CascadeType.ALL)
private Organisation organisation;
@ManyToOne(cascade = CascadeType.ALL)
private Role role;

public Contact() {

}

public Contact(String phoneNumber, String firstName, String surname,
String email, Organisation organisation, Role role) {
this.phoneNumber = phoneNumber;
this.firstName = firstName;
this.surname = surname;
this.email = email;
this.organisation = organisation;
this.role = role;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getSurname() {
return surname;
}

public void setSurname(String surname) {
this.surname = surname;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public Organisation getOrganisation() {
return organisation;
}

public void setRole(final Role pRole) {
role = pRole;
}

public Role getRole() {
return role;
}

public void setOrganisation(Organisation organisation) {
this.organisation = organisation;
}

public int getId() {
return id;
}

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

@Override
public String toString() {
return new StringBuilder(surname).append(", ").append(firstName)
.toString();
}
}

@Entity
@Table(schema = "reskonverw")
public class Country {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
private String name;

public Country() {
}

public Country(String cName) {
this.name = cName;
}

public int getId() {
return id;
}

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

public String getName() {
return name;
}

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

@Override
public String toString() {
return name;
}
}

@Entity
@Table(schema = "reskonverw")
public class Organisation {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
private String name;
private String zipcode;
private String housenumber;
private String city;
private String street;
@ManyToOne(cascade = CascadeType.ALL)
private Country country;

public Organisation() {
}

public Organisation(String name, String zipcode, String housenumber,
String city, String street, Country country) {
this.name = name;
this.zipcode = zipcode;
this.housenumber = housenumber;
this.city = city;
this.street = street;
this.country = country;
}

public int getId() {
return id;
}

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

public String getName() {
return name;
}

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

public String getZipcode() {
return zipcode;
}

public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}

public String getHousenumber() {
return housenumber;
}

public void setHousenumber(String housenumber) {
this.housenumber = housenumber;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public Country getCountry() {
return country;
}

public void setCountry(Country country) {
this.country = country;
}

@Override
public String toString() {
return name;
}
}

@Entity
@Table(schema = "reskonverw")
public class Role {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
private String description;

public Role() {
}

public Role(String rDescription) {
this.description = rDescription;
}

public int getId() {
return id;
}

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

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

@Override
public String toString() {
return description;
}
}

我的 session bean,用于显示在javafx表中

public class OrganisationContact {
private Contact contact;

public OrganisationContact(Contact contact) {
this.contact = contact;
}

/* Entities */
public Organisation getOrganisation() {
return contact.getOrganisation();
}

public void setOrganisation(Organisation organisation) {
contact.setOrganisation(organisation);
}

public Contact getContact() {
return contact;
}

public void setContact(Contact contact) {
this.contact = contact;
}

public Role getRole() {
return contact.getRole();
}

public void setRole(final Role pRole) {
contact.setRole(pRole);
}

public Country getCountry() {
return contact.getOrganisation().getCountry();
}

public void setCountry(final Country pCountry) {
contact.getOrganisation().setCountry(pCountry);
}

/* EntityStats */
// Organisation

public String getOrganisationName() {
return contact.getOrganisation().getName();
}

public void setOrganisationName(final String pName) {
contact.getOrganisation().setName(pName);
}

public String getOrganisationZipcode() {
return contact.getOrganisation().getZipcode();
}

public void setOrganisationZipcode(final String pZipcode) {
contact.getOrganisation().setZipcode(pZipcode);
}

public String getOrganisationHousenumber() {
return contact.getOrganisation().getHousenumber();
}

public void setOrganisationHouseNumber(final String pHouseNumber) {
contact.getOrganisation().setHousenumber(pHouseNumber);
}

public String getOrganisationCity() {
return contact.getOrganisation().getCity();
}

public void setOrganisationCity(final String pCity) {
contact.getOrganisation().setCity(pCity);
}

public String getOrganisationStreet() {
return contact.getOrganisation().getStreet();
}

public void setOrganisationStreet(final String pStreet) {
contact.getOrganisation().setStreet(pStreet);
}

// Contact
public String getFirstName() {
return contact.getFirstName();
}

public void setFirstName(final String pFirstName) {
contact.setFirstName(pFirstName);
}

public String getSurname() {
return contact.getSurname();
}

public void setSurname(final String pSurname) {
contact.setSurname(pSurname);
}

public String getEmail() {
return contact.getEmail();
}

public void setEmail(final String pEmail) {
contact.setEmail(pEmail);
}

public String getPhoneNumber() {
return contact.getPhoneNumber();
}

public void setPhoneNumber(final String pPhoneNumber) {
contact.setPhoneNumber(pPhoneNumber);
}

// Country
public String getOrganisationCountryName() {
return contact.getOrganisation().getCountry().getName();
}

// Role
public String getRoleDescription() {
return contact.getRole().getDescription();
}

public void setRoleDescription(final String pDescription) {
contact.getRole().setDescription(pDescription);
}
}

编辑:当在程序启动时进行选择时,sql hibernate 首先在我的控制台上打印:

Hibernate: 
select
*
from
( select
contact0_.id as id1_0_,
contact0_.email as email2_0_,
contact0_.firstname as firstname3_0_,
contact0_.organisation_id as organisation_id6_0_,
contact0_.phonenumber as phonenumber4_0_,
contact0_.role_id as role_id7_0_,
contact0_.surname as surname5_0_
from
reskonverw.Contact contact0_ )
where
rownum <= ?
Hibernate:
select
organisati0_.id as id1_2_0_,
organisati0_.city as city2_2_0_,
organisati0_.country_id as country_id7_2_0_,
organisati0_.housenumber as housenumber3_2_0_,
organisati0_.name as name4_2_0_,
organisati0_.street as street5_2_0_,
organisati0_.zipcode as zipcode6_2_0_,
country1_.id as id1_1_1_,
country1_.name as name2_1_1_
from
reskonverw.Organisation organisati0_
left outer join
reskonverw.Country country1_
on organisati0_.country_id=country1_.id
where
organisati0_.id=?
Hibernate:
select
role0_.id as id1_3_0_,
role0_.description as description2_3_0_
from
reskonverw.Role role0_
where
role0_.id=?

这里,当单击按钮进行删除时,sql hibernate 在我的控制台上打印(选择是因为我之后更新所有实体,因为有多个客户端):

Hibernate: 
delete
from
reskonverw.Contact
where
id=?
Hibernate:
select
*
from
( select
contact0_.id as id1_0_,
contact0_.email as email2_0_,
contact0_.firstname as firstname3_0_,
contact0_.organisation_id as organisation_id6_0_,
contact0_.phonenumber as phonenumber4_0_,
contact0_.role_id as role_id7_0_,
contact0_.surname as surname5_0_
from
reskonverw.Contact contact0_ )
where
rownum <= ?

这里,sql hibernate 在单击按钮时执行更新而不是删除时在我的控制台上打印(没有选择,因为它之前崩溃了):

Hibernate: 
update
reskonverw.Contact
set
email=?,
firstname=?,
organisation_id=?,
phonenumber=?,
role_id=?,
surname=?
where
id=?
Jul 08, 2015 8:05:12 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1407, SQLState: 72000
Jul 08, 2015 8:05:12 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-01407: Aktualisieren von ("RESKONVERW"."CONTACT"."ORGANISATION_ID") zu NULL nicht möglich

对于非德国人,“错误:ORA-01407:Aktualisieren von(“RESKONVERW”。“CONTACT”。“ORGANISATION_ID”)zu NULL nicht möglich”意味着“错误 - 将 resconverw.contact.organization_id 设置为 null 不可能

最佳答案

联系人有组织的外键。它通过组织的 ID 链接。当我删除联系人时,Hibernate 有时会在删除之前尝试将 foreginkey 设置为 null。并不总是因为某种我还不明白的原因。在我的数据库中,我设置了一个约束,防止外键变为空。这就是更新失败并且我遇到异常的原因。我删除了限制,从那时起它就开始工作了。

感谢大家的帮助

关于java - Hibernate (JPA) - 无缘无故的奇怪更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31267213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com