I have two tables website_availability and status_codes.And these have foriegn key relation between them.status_codes is parent table.I am using hibernate.I need "list" of values from these tables after joining.I am following this code.
List<WebsiteAvailability>list=new ArrayList<WebsiteAvailability>
String selquery="select w.statusCode,w.updateTime,w.statusCodes.statusCodeValue from WebsiteAvailability w,StatusCodes s where w.statusCodes.statusCode=s.statusCode and w.url=?";
//here hibernate generates the POJO classes and these are having foriegn key relation so WebsiteAvailability is having private StatusCodes statusCodes.So I am accessing statuscodevalue of statuscodes table using w.statusCodes.statusCodeValue.
PreparedStatement ps=con.prepareStatement(selquery);
ps.setString(1,selUrl);
rs=ps.executeQuery();
while(rs.next())
{
list.add(new WebsiteAvailability(rs.getString("statusCode"),rs.getTimestamp("updateTime"),rs.getString("statusCodeValue")));
}
return list;
}
First of all can I use resultset with hibernate.Is there any alternative for this.Because as I am using ? placeholder I should use preparedstatement for setString().And executeQuery() to get the list.I need list of values how can i get.Am getting empty list.What is the error?
org.hibernate.QueryException:could not resolve the property statusCode of -----WebsiteAvailability---
In the hibernate mapping file I have checked for case sensitivity.Still getting could not resolve property exception
You're trying to execute an HQL query, working on Hibernate entities, as a SQL query, using JDBC statements. That doesn't make sense. HQL queries are executed by the Hibernate Session. Not by JDBC. If you're using Hibernate, you don't need JDBC anymore (except maybe in some corner cases when you need raw JDBC performance, like batches).
Read the documentation about HQL query execution. You'll also have to fix your query, because it doesn't seem right. It contains w.statusCode and also w.statusCodes. It also does a join using equality statements and selects from two entities, instead of simply using implicit or explicit joins. Those are also explained in the documentation.
Related
I wanted to perform the Spring JPA repository where wanted to apply the and operation among 2 columns where one column cloud have multiple values in it.
SQL query for the same:
select * from table_name where col1='col1_val' and col2 IN
('col2_val_a','col2_val_b','col2_val_c');
I know that for and operation I can extend the JpaRepository and create the method with like this for:
List<MyPoJoObject> findByCol1AndCol2(String col1_val,String col2_val);
and for IN operation we can use : findByCol2In(Collection<String> col2_val)
But i did not know how i can club both the mentioned JPA default method into one, as per my sql statement mentioned before.
You can use the following method named:
List<MyPoJoObject> findByCol1AndCol2In(String col1_val, Collection<String> col2_val);
On this link repository-query-keywords you can find repository query keywords that you can use and combine them as well.
You can certainly combined both into one method.
List<MyPoJoObject> findByCol1AndCol2In(String col1_val,String[] col2_val);
Try this. I am not sure if it will accept Collection<String>. I will try that and update the answer.
HTH.
If you want to perform this logic for more than two columns then your method name becomes verbose.
Instead of stuck with Spring naming why can't you write your own JPA query.
Example:
#Query("select pojo from MyPoJoObject as pojo where pojo.col1 = :col1_val and pojo.col2 in :col2_val")
List<MyPoJoObject> findByColumns(String col1_val, List<String> col2_val);
I have my service up and running but there's still a few things i can't figure out.
I have a query that is similar to the following
#Query("SELECT t FROM Tablename t")
Then hibernate will generate the following query
Hibernate: select tname.column1 as a, tname.column2 as b, tname.column3 as c, tname.column4 as d from tablename tname
The problem is that Tablename is case sensitive when i query against a mysql database. Is there a way in hibernate to execute the query exactly the way it is spelled out in the annotation? Also, is it possible to stop hibernate from breaking camelcased columns into two works. For example if i had a column named columnOne hibernate will want to generate a column with the name column_one.
I know this more than likely has something to do with hibernate's naming strategy but i haven't been able to find a solution.
Try adding the following in your application.properties file.
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Documentation about naming strategies are here
I have many EntityManager, one per schema that I have (I use entity-mappings file to map EMs with schemas). It works.
When I use #NamedQuery it's working like a charm but when I use #NamedNativeQuery schema is not used. I have to qualify with it SELECT foo FROM schema.table.
Is it the right behaviour ?
I think it's not possible to parameter #NamedNativeQuery to dynamically pass schema (I believe only columns can be dynamics not tables or schemas or anything else) so how can I use #NamedNativeQuery with dynamic schema please ?
Prefix your table name with "{h-schema}", e.g.SELECT foo FROM {h-schema}table
(courtesy of getting hibernate default schema name programmatically from session factory?)
Excerpts from documentation :
NamedNativeQuery : Specifies a named native SQL query. Query names are scoped to the persistence unit.
NamedQuery : Specifies a static, named query in the Java Persistence query language. Query names are scoped to the persistence unit.
It isn't specified directly that NamedNativeQuery is static, but both are same scoped & can't be altered afterwards & it's the desired behaviour.
Named queries are mean to be accessed by multiple modules - application wide, identified by unique name, so they are static & constant. You can try building a query string dynamically & can create a native query from it, instead of named native query.
I'm working with JPA2 and Hibernate 3, using MySQL for a database. There is class a TestB as follows:
#SQLInsert(sql = "INSERT IGNORE INTO testB (....) VALUES (?,?,?,?,?,?) ;")
class TestB{
#GeneratedValue(strategy=GenerationType.IDENTITY)
#ID
private long id;
#Column(unique)
String ccc;
}
For the transaction start:
#Transactional
List<TestB> list = ...
repoitory.save(list);
But unfortunately, this is a bulk insert, so I cannot save all of the data in memory. What I chose to do is, just pass the data to the database, and the database decides what to do.
For pure SQL, INSERT IGNORE works just fine. But for Hibernate, I tried two things.
1. Insert Ignore
2. Insert .. on duplicate update (...)
Neither work. The errors for each are,
1. The database returned no natively generated identity value.
2. NonUniqueObject Exception.
Both happen for the duplicate entry, not the first one.
I assume that the first error occurred because after insert, Hibernate should assign an ID to the proxy object, but it can't. I assume the second error occurred because two objects with same ID cannot existed in the same session.
How can I resolve this issue?
In the first case, hibernate tries to insert data into the table if there is no constraint violations or sql errors. If there are any exceptions (say unique key violations.. ) since you have used INSERT IGNORE DB doesn't insert anything into the DB, so there is no ID which is generated natively; Hibernate throws a system Exception with the error The database returned no natively generated identity value.
One of the Solutions: Well one way of handling this error is to catch HibernateSystemException, which is thrown when insert fails and is ignored by MySQL DB.
Since this is an hibernate system exception, Hibernate internally seems to mark the transaction for rollback even if one of the ignore fails. I am trying to find a solution to this as well.
I am using Hibernate 4.2.4 and I am interested to know how Hibernate translate a session.get call to an equivalent sql query that is eventually used to retrieve rows from database. I do not want to log the generated sql in console. I want to use the same sql query in my application. Something like below.
...
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.buildServiceRegistry());
// I want the query string here
String query = sessionFactory.someUnknownMethod(Some Paramters);
Session session = sessionFactory.openSession();
// actual session.get query
Comment comment = (Comment) session.get(Comment.class, new Integer(1));
...
I have seen this thread for Criteria query -> How to get SQL from Hibernate Criteria API (*not* for logging).
I would like to know if similar procedure exists for session.get type queries.
I have also seen this thread -> get SQL from hibernate get
where the question is exactly same as mine, but the accepted solution talks about fetching statistics which, to my understanding, only accounts for the queries that have already been executed. Plus, from statistics I was able to catch hql/sql queries but not session.get queries.
I want to know if there is a way for a user to generate and use the sql even before the actual session.get gets executed (possibly by following the same path as hibernate).