[Hibernate] NamedQuery nur einzelne Felder

turmaline

Bekanntes Mitglied
Hallo,

ich stelle eine Anfrage an die Attachment-Klasse, möchte aber nur 2 Felder zurückbekommen.
Die Anfrage sieht foldendermassen aus:

Java:
@NamedQuery(name = "attachment.commentAndAtt", query = "select a.id, a.name from Comment c, Attachment a where c.id = :id and c.attachment.id = a.id")

Wie man aus der Anfrage sieht, möchte ich nur die id und den Namen von einem Attachment zurückerhalten.
Leider kriege ich eine ClassCastException wenn ich versuche as Ergebnis auszulesen:

Java:
Attachment a = getSingleResult(attQuery, Attachment.class);

Was mach ich falsch bzw wie kann ich eine Copie erzeugen die nur id und den namen enthält.

Eine equivalente sql anfrage würde aussehen

SQL:
SELECT a.id, a.name
FROM comment c, attachment a
where c.id=???
and c.attachmentId = a.id

Kann mir jemand helfen????:L bitte😳

gruß, madlena
 
habe das hier gefunden:

Hibernate - nur bestimme Spalten aus DB lesen @ tutorials.de: Tutorials, Forum & Hilfe

nun sieht meine anfrage so aus:

Java:
@NamedQuery(name = "attachment.commentAndAtt", query = "select new Attachment(a.id, a.name) from Comment c, Attachment a where c.id = :id and c.attachment.id = a.id")

dafür musste ich einen Konstruktor hinzufügen:

Java:
public Attachment(Long id, String name) { //  TODO
    	this.id = id;
    	this.name = name;
    }

ich bin noch dabei zu schauen ob das funktioniert.. jedenfalls bekomme ich keine exception mehr. ich werde noch berichten ob es geklappt hat
 

Neue Themen


Zurück
Oben