java - Hibernate model OneToOne do not share entire object? -
i discovering jpa , hibernate , have question repository , model (using spring).
i have object "structure" fields ( id , type example ) , lot of others objects related structure : example address. address in addressrepository :
address findbystructureid(long structureid);
but way found have object structure in object address. don't know if problem or not according memory because structure big object lot of subobjects address.
in structure
@onetoone(fetch = fetchtype.lazy, mappedby = "structure", cascade = cascadetype.all) private address address;
in address
@genericgenerator(name = "generator", strategy = "foreign", parameters = @parameter(name = "property", value = "structure")) @id @generatedvalue(generator = "generator") private long structureid; @onetoone(fetch = fetchtype.lazy) @primarykeyjoincolumn @jsonignore private structure structure;
i have problem architecture. need keep "sub objects" of structure year don't know how it. example, address of structure #1 year #2012.
i'll try answer , see several ways improve code.
i don't know if problem or not according memory because structure big object lot of subobjects address.
it's not problem, lazy-loading. if load address object, never call getstructure method (or structure object internally) structure object never loaded db.
now address class :
@genericgenerator(name = "generator", strategy = "foreign", parameters = @parameter(name = "property", value = "structure")) @id @generatedvalue(generator = "generator") private long structureid;
why have structureid
generated primary key ?
the proper way have id
field generated pk. , separate structureid
field fk pointing structure
table. structureid
field exist in db not field of address class. used key in relationship annotation.
also recommend using long
objects instead of long
primary datatypes key.
the main reason object can null
, , useful when using jpa, in order determine if entity has been persisted or newly created. guess long have value of zero, , check that, seems less safe.
also it's easier if want use java collections ids. example can't use long
map
key can use long
object.
finally, regarding dated sub-objects, require different table , class structure.
for one, relationship become many-to-one (the many side being address
) , address (and other) objects have year
field, or better startdate
, enddate
fields (so if address didn't change, not duplicated). or have third table year
, address point structure. depends on requirements.
Comments
Post a Comment