i have problem handle mapping object relationship mysql tables. have 2 tables shown below:
device ----------- deviceid pk devicename apkinfo -------- id pk packagename appname deviceid fk
and here classes:
@entity @table(name="device") public class device implements serializable { @column @id private string deviceid; @column private string devicename; //getters , setters } @entity @table(name="apkinfos") public class apkinfo implements serializable { @column @id @generatedvalue(strategy=generationtype.auto) private int id; @column @id private string packagename; @column private string appname; @column @temporal(temporaltype.timstamp) private date installdate; @manytoone @joincolumn(name="deviceid" referencedcolumnname="deviceid") private device device; //getters , setters }
this works me, want use compound key, deviceid
, packagename
, in apkinfos
table.
@entity @table(name="apkinfos") public class apkinfo implements serializable { @colum(instable=false, updatable=false) @id private string deviceid; @column private string packagename; @column private string appname; @manytoone @joincolumn(name="deviceid" referencedcolumnname="deviceid") private device device; //getters , setters }
but when tried save entity using spring data jpa repository, got error:
org.springframework.dao.invalidaccessapiusageexception: class must not null, nested exception java.lang.illegalargumentexception: class must not null
apkinfo apkinfo = new apkinfo(); apkinfo.setdeviceid("1234"); apkinfo.setpackagename("aaa"); apkinfo.setappname("myapp"); apkinfo.setinstalldate(new date()); apkinfo.setdevice(new device("1234")); repository.save(apkinfo);
and device has deviceid
'1234' exists in device table.
i created separate primary key class added @idclass in apkinfo class. works fine now, thanks. going have @ embeddedid more later.
i added @idclass @ entity class , @id packagename property. made insert, update false one-to-many column.
@entity @table(name="apkinfos") @idclass(apkinfo.class) public class apkinfo implements serializable { @column @id private string deviceid; @column @id private string packagename; @manytoone @joincolumn(name="deviceid" referencedcolumnname="deviceid", insetable=false, updatable=false) private device device; //getters , setters missing }
primary key class has setters , overrides equals , hascode methods.
public class apkinfo implements serializable { private string deviceid; private string packagename; public apkinfo(){} public apkinfo (string deviceid, string packagename){ this.deviceid = deviceid; this.packagename = packagename; } public string getdeviceid(){ return this.deviceid; } public string getpackagename(){ return this.packagename; } @override public boolean equals(object obj){ return (obj!=null && obj instanceof apkinfopk && deviceid.equals(((apkinfopk)obj).getdeviceid()) && packagenames.equals(((apkinfopk)obj).getpackagename()) ); } @override public int hashcode(){ super.hashcode(); } }
Comments
Post a Comment