Select one column from a row in hibernate - mysql

I am trying to do a simple query to get a unique result back in hibernate here is my code.
public String getName(Integer id) {
Session session = getSessionFactory().openSession();
String name = (String)session.createSQLQuery("SELECT name FROM users WHERE user_id = :userId").setParameter("userId", id).uniqueResult();
return name;
}
The name that is being returned is stored as HTML text that includes html syntacx language. I think this is what is causing the problem but it doesnt make sense I just want to return it as a string.
It is only happening on this one field name, I can get every other field in the row but this one it gives me the error.
I am getting an exception. The exception I am getting is
No Dialect mapping for JDBC type: -1; nested exception is org.hibernate.HibernateException
How do you query for a specific column on a row in hibernate?

I figured out the solution, apparently Java has not type that can be mapped to Text fields so you have to add a scalar solution below: Thanks for the help
session.createSQLQuery("SELECT name FROM users WHERE user_id = :userId").addScalar("name", Hibernate.TEXT).setParameter("userId", id).uniqueResult();

Then that should work. Use the Type hibernate annotation.
Add
#Type(type="text")
To your mapping.

Related

Spring data Couchbase #n1ql.fields query

I'm trying to make a N1QL based query on Spring Data Couchbase. The documentation says
#n1ql.fields will be replaced by the list of fields (eg. for a SELECT clause) necessary to reconstruct the entity.
My repository implementation is this one:
#Query("#{#n1ql.fields} WHERE #{#n1ql.filter}")
List<User> findAllByFields(String fields);
And I'm calling this query as follows:
this.userRepository.findAllByFields("SELECT firstName FROM default");
I'm getting this error:
Caused by: org.springframework.data.couchbase.core.CouchbaseQueryExecutionException: Unable to execute query due to the following n1ql errors:
{"msg":"syntax error - at AS","code":3000}
After a little bit of researching, I also tryed:
#Query("SELECT #{#n1ql.fields} FROM #{#n1ql.bucket} WHERE #{#n1ql.filter}")
With this query, I don't get an error, I get all the documents stored but only the ID the other fields are set to null, when my query tries to get the firstName field.
this.userRepository.findAllByFields("firstName");
Anyone knows how to do such a query?
Thank you in advance.
You're misunderstanding the concept, I encourage you to give the documentation more time and see more examples. I'm not sure what exactly you're trying to achieve but I'll throw some examples.
Find all users (with all of their stored data)
#Query("#{#n1ql.selectEntity} WHERE #{#n1ql.filter}")
List<User> findAllUsers();
This will basically generate SELECT meta().id,_cas,* FROM bucket WHERE type='com.example.User'
Notice findAllUsers() does not take any parameters because there are no param placeholders defined in the #Query above.
Find all users where firstName like
#Query("#{#n1ql.selectEntity} WHERE #{#n1ql.filter} AND firstName like $1")
List<User> findByFirstNameLike(String keyword);
This will generate something like the above query but with an extra where condition firstName like
Notice this method takes a keyword because there is a param placeholder defined $1.
Notice in the documentation it says
#{#n1ql.selectEntity} WHERE #{#n1ql.filter} AND test = $1
is equivalent to
SELECT #{#n1ql.fields} FROM #{#n1ql.bucket} WHERE
#{#n1ql.filter} AND test = $1
Now if you don't want to fetch all the data for user(s), you'll need to specify the fields being selected, read following links for more info
How to fetch a field from document using n1ql with spring-data-couchbase
https://docs.spring.io/spring-data/couchbase/docs/2.2.4.RELEASE/reference/html/#_dto_projections
I think you should try below query, that should resolve the issue to get fields based parameter you have sent as arguments.
Please refer blow query.
#Query("SELECT $1 FROM #{#n1q1.bucket} WHERE #{#n1ql.filter}")
List findByFirstName(String fieldName);
Here, bucket name resolve to the User entity and and n1ql.filter would be a default filter.

FindBy columnName when column name contains "Id"

In Grails, Gorm, I have this entity:
class MyEntity implements Serializable {
Long bankTransactionId
int version
BigDecimal someValue
static constraints = {
bankTransactionId(nullable: false)
version(nullable: true)
someValue(nullable: true)
}
}
Doing MyEntity.findByBankTransactionId(Long.valueOf("3")) throws this exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown
column 'this_.id' in 'field list'
I am suspecting the fact that my column has the name id in it. Could it be this?
How to fix it then ?
Thanks.
Everything you have provided here looks fine. In particular, there are no restrictions about having the letters "id" in a column name.
Take a look at your generated MySQL table. I'm guessing that the id column isn't there for some reason. Maybe something prevented generating it due to some earlier error that you have now corrected, or you have your datasource set to "none" instead of "update" (or similar) and the whole table is missing!
If this is just a development environment with no real data (and no foreign key constraints), drop the whole MyEntity table and let it be automatically recreated. If not, move to a different temporary datasource, let a new table be created, and compare the two. If the new one still doesn't have an id column, you have something going wrong during your startup that is preventing your tables from being created correctly. You could just add the column in manually, but if you don't figure out what happened to it in the first place, it will probably just happen again.
For reference, in my test environment, my MySQL table for "MyEntity" copied from your example looks like:
desc my_entity;
'id','bigint(20)','NO','PRI',NULL,'auto_increment'
'version','int(11)','YES','',NULL,''
'bank_transaction_id','bigint(20)','NO','',NULL,''
'some_value','decimal(19,2)','YES','',NULL,''

Getting Error message from linq to entity query.

I keep receiving the error
"LINQ to Entities does not recognize the method 'System.String get_Item(Int32)' method, and this method cannot be translated into a store expression"
on the following line in my code
var Reviewer = repository.reviewers.FirstOrDefault(t => t.ReviewerName == formCollection[3]);
formCollection[3] is a string returned from a drop down I have contained within a form. The query seems to work O.K. until it returns the value from the database. What can I do to fix this?
OK, I was trying to do too much at once, when I finally thought about it and put formCollection[3] into a string variable and then used the string variable in the linq query everything worked out ok.

Is there a way to avoid wasNull() method?

I have a big ResultSet (getting from a JDBC query) of few thousand rows. Using each of these rows, I have to instantiate an Object, setting fields of it according to the fields of this result set. Now, as we all know, the getXXX() methods of this JDBC API return 0 if that particular column was null. So for each field of each row, I have to do a wasNull() before setting the value in my object, which looks pretty ugly and may be is not efficient as well. So, is there any other way by which I can avoid it?
Apart from JDBC, if there is some entirely different, standard, commonly used way, I am open to know about that as well.
Thanks!
EDIT 1
patientInput.setRaceCodeId(patients.getShort("race_code_id"));
if(patients.wasNull())
patientInput.setRaceCodeId(null);
patients is a ResultSet. patientInput is an object. This is the code which I am trying to avoid. I mean, everytime I do a getXXX(), and do a setXXX(), I have to check again that what I got from ResultSet was not null. If it was, then set that object field as null, as getXXX() returns 0 in that case.
Ok. I believe there are two possible approaches to 'tidying' up your code. However, this could come down to a difference of opinion as to what is tidy!
Solution 1 - replace getXXX() with getObject() which returns null e.g.
Short s = (Short)patients.getObject("race_code_id");
patientInput.setRaceCodeId(s);
Solution 2 - write a generic wrapper method that retrieves nullable values
protected final <T> T getNullableValue(T returnType, String colName, ResultSet rs) throws SQLException {
Object colValue = rs.getObject(colName);
return (T) colValue;
}
final static Integer INT = 0;
final static Short SHORT = 0;
.
.
.
patientInput.setRaceCodeId(getNullableValue(SHORT,"race_code_id",patients));
You don't have to do it to each field, only to fields that are numeric and, possibly, boolean, and are declared as nullable in your database. It happens not as frequently as you fear.
If you absolutely hate writing such code, you can try switching to an ORM library, for example, Hibernate.

Hibernate JPA Template fetch

Hibernate JPA Template fetches list of objects from database.
Can this be type casted to another class object list??
List<Class1> list1 = (List<Class1>) getJpaTemplate().findByNamedQuery("..someQuery..");
This is the code which i use now. Class1 relates to a table1 in database. Will I be able to fetch the records in table1 into another list<Class2> list2; which has all parameters as table1 and some extra parameters. If I will be able to fetch then will I be able to assign values to those extra parameters through namedQuery ??
Any help appreciated!!
Yes, you can. But before you have some more concrete questions, go read the following:
Hibernate inheritance
and JPA-QL reference, point 7.7, where they explain cat.class