Reputation: 204
I have an application with default values persisted in the database. For example, a class Person with an attribute City wich default is "New York" with the id 0.
@Entity
public class Person {
@Id
private Integer personId;
private String name;
@ManyToOne
private City city;
}
@Entity
public class City {
@Id
private Integer cityId;
private String cityName;
}
And in database :
+--------+------------+
| cityId | cityName |
+--------+------------+
| 0 | 'New York' |
+--------+------------+
And what I want to do is to save a new Person :
Person p = new Person();
p.setName("Smith");
personRepository.save(p);
If i try to create a city instance whith id 0 and name "New York" I will have a "TransientObjectException: object references an unsaved transient instance" : definitely not a good solution.
If I put a default value in the table definition I will have to reload entity from database after saving it.
I could load the city before saving the Person, but I will have also 2 access to the database.
These two solutions are not good for me because I have to explicitely load City instance from database. Is there a way to do it automatically ? (maybe an interceptor or something like that)
NB: I use hibernate 4 and spring 3.2
Upvotes: 0
Views: 1010
Reputation: 242686
If i try to create a city instance whith id 0 and name "New York" I will have a "TransientObjectException: object references an unsaved transient instance"
It should not be so. Perhaps it's caused by the fact that id
of default city is 0
. Try to use 1
instead.
Alternatively, you can obtain a lazy proxy without touching the database using Session.load()
/EntityManager.getReference()
.
Upvotes: 1