java - Repository Inheritance -
i create repository performs basic crud operations.
since have different kind of photos (companyphoto, carphoto, ..), prefer make jpa repository generic, ejb service well.
here classes:
@entity @inheritance @discriminatorcolumn(name = "descriminator") @table(name = "photos") public abstract class photo { public photo() { } public photo(string filename) { this.filename = filename; // this.file = file; } @id @generatedvalue(strategy = generationtype.table, generator = "photos_seq") @tablegenerator(name = "photos_seq", table = "sequence", pkcolumnname = "seq_name", pkcolumnvalue = "photos_seq", valuecolumnname = "seq_count", allocationsize = 50) @column(nullable = false) private long id; @column(length = 255) @size(min = 0, max = 255, message = "{photo.description.size}") protected string description; @column(nullable = false, length = 255) @notnull(message = "{photo.filename.notnull}") @size(min = 1, max = 255, message = "{photo.filename.size}") protected string filename; // ... @entity @discriminatorvalue("c") public class carphoto extends photo { public carphoto() { } public carphoto(string filename) { super.filename = filename; } @manytoone(cascade = { cascadetype.detach }) @joincolumn(name = "carid", nullable = false) @notnull private car car; // ... @entity @discriminatorvalue("p") public class personphoto extends photo { public personphoto() { } public personphoto(string filename) { super.filename = filename; } @manytoone(cascade = { cascadetype.detach }) @joincolumn(name = "personid", nullable = false) @notnull private person person; // ... @stateless @localbean public class photorepository<e> { // in class create, remove, update , basic find //operations.. @persistencecontext private entitymanager em; public photorepository() { } photorepository(entitymanager em) { this.em = em; } @override public e create(e photo) { em.persist(photo); return photo; } @override public e modify(e photo) { class<e> photoclass; // question: how going call getid() method object of type e class? em.find(photoclass, photo.getid()); // not work.. =( e mergedphoto = em.merge(photo); return mergedphoto; } // ... i hope understand want perform. generic repository different kind of classes inherit same baseclass. can give me best practices examples? =)
best regards
change generics definition e has type extends photo. able access methods of photo class on variables of type e
@stateless @localbean public class photorepository<e extends photo> { you can use following method retrieve actual class.
public class getentityclass() { parameterizedtype parameterizedtype = (parameterizedtype) getclass().getgenericsuperclass(); return (class) parameterizedtype.getactualtypearguments()[0]; } ir using spring should take @ spring-data-jpa - provides such generic repositories implementation.
Comments
Post a Comment