4

I'm fairly new to JPA/Hibernate. My issue involves a couple of existing database tables as shown below:

CREATE TABLE `person` (
  `personId` int(11) NOT NULL,
  `name` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '',
  `addressId` int(11) NOT NULL DEFAULT 0,
  PRIMARY KEY (`personId`)
);

CREATE TABLE `address` (
  `addressId` bigint(20) NOT NULL,
  `address` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '',
  PRIMARY KEY (`addressId`)
);

The entities are implemented as such:

@Entity
public class Person {
  @Id
  private Integer personId;

  private String name;

  @ManyToOne
  @JoinColumn(name="addressId")
  private Address address;
}

@Entity
public class Address {
  @Id
  private Integer addressId;

  private String address;

}

Multiple people can live in the same address. A person can also not have an address. The addressId from the person table is essentially an optional field. There is no addressId = 0 in the address database. The value 0 is basically used as if it was a null parameter.

My issue is getting this to happen when I try to persist a person into table where the addressId = 0.

If I set the Address object within the Person to null, I would get the following error:

"addressId cannot be null"

If I set the address object to have an addressId of 0, I get this other transientObjectError, which is returned because there's no entry in the address table with the addressId = 0.

I tried using @PrePersist to try to attempt to set the default values before the object gets persisted, however, I get the same two errors above. Same thing when I add optional=true in the @ManyToOne.

I don't think inserting an dummy address with id=0 is a good idea.

Any ideas if it's possible to use the @ManyToOne annotation and still have a default value of 0 where 0 is not an actual entry in the database?

learning2code
  • 41
  • 1
  • 2

2 Answers2

0

If you really have to keep these 0 instead of null maybe you can try with a CustomType. See here: Hibernate Many-To-One Foreign Key Default 0

Community
  • 1
  • 1
Julien
  • 1,087
  • 7
  • 15
  • Thanks for the link. After creating a custom userType, I get the error: "javax.persistence.EntityNotFoundException: Unable to find Address with id 0". This seems similar to the issue about having no entry with the ID of 0 (since it's a dummy row). – learning2code May 15 '15 at 21:37
0

I had the same problem, I solved it using @NotFound annotation with the action NotFoundAction.IGNORE, which will return null if an associated entity doesn't exist.

Example:

import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

@ManyToOne
@NotFound( action = NotFoundAction.IGNORE )
private Module module;
Ousama
  • 2,176
  • 3
  • 21
  • 26