Reputation: 1219
I have tried to model just a few columns for a already created table. But Hibernate
can´t perform queries able to return data for the application.
I'm doing something like this in the model that maps a created table:
@Column(name="LOCALE_ID")
private String locale;
@Id
@Column(name="ID")
private Long ID;
@Column(name="TITLE")
private String title;
public Location () {}
public Long getID() {
return ID;
}
public void setID(Long ID) {
this.ID = ID;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
The method that performs the query is shown below:
String q = "SELECT l.title FROM " + className +
" l WHERE l.locale = '" + locale + '"';
List<Location> result = null;
try {
Transaction tx = getSession().beginTransaction();
result = (List<Location>)session.createQuery(q).list();
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
When i called this method with correct parameters, nothing is returned, but the mapped table contains data that can be fetched with those parameters.
I dont know why the hibernate can´t handle with created tables.
Maybe an reverse engineering to generate the model, can help, but i dont know how to perform this.
Any thoughs on this?
Upvotes: 0
Views: 61
Reputation: 1219
The best way to perform the search is with constructor expression in the SELECT, see it below:
String q = "Select new " + className + "(l.ID, l.title, l.locale) From " + className + " l Where l.locale = '" + locale + "'";
Upvotes: 0
Reputation: 3467
You are shadowing your List result in the try/catch block with an equally named, but new variable, to which you assign the results of the query. But you always return the outer variable assigned to null.
String q = "SELECT l.title FROM " + className +
" l WHERE l.locale = '" + locale;
List<Location> result = null;
try {
Transaction tx = getSession().beginTransaction();
result = (List<Location>)session.createQuery(q).list();
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
might do better
Upvotes: 1
Reputation: 32535
You should use query ability to specify parameters, as probably this will be the issue. Try something like this
String q = "SELECT l.name FROM yourclassname l WHERE l.locale=:locale";
List<Location> result = null;
try {
Transaction tx = getSession().beginTransaction();
session=yourFactory.openSession();
query=session.createQuery(q);
query.setParameter("locale",yourLocaleVal);
result=query.list();
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
Upvotes: 0