Connecting Java Object with MySql Tables - java

I am working with Java Classes, and I'm looking for the easiest way to connect a DB table in MySQL with the members (attributes) to the Java code.
After executing the "SELECT" query I get a resultSet, yet it is not clear to me how to cast the result Object to the Java Object generically.
For Example: I have 2 Java Classes - Student & Teacher, and I would like to use a command:
Student student = (Student) rs.getObject();
Thanks,
Roi

I would recommend using JPA with eclipselink implementation, rathern than executing queries using plain JDBC, and try to map results from resultsets to objects by hand (error prone). JPA will do that for you !

this doesn't work in that way. You should do something like:
Student st = new Student();
st.setName(rs.getString("NAME"));
st.setAverage(rs.getInt("SCORE"));
where NAME and SCORE are the column names.
The doc can also help you.

You can look at ORM solutions, like Hibernate.

If your question is about rs.getObject.
The call rs.getObject is a generic way of calling rs.getInt, rs.getString because the return values of all these methods are ultimately Objects (Int, String etc...).
It will return the column you ask for (either by order number in the select or by column name). Not the whole bean corresponding to a row.
You use rs.getObject when you do not know at compilation time the type of the returned column.
The JDBC ResultSet Object does not have a magic getObject method that will return the bean corresponding to a select statement.
You can develop your own 'poor man's ORM' with combination of
JBBC ResultSetMetaData
Java Reflexion
But that's a harder work than using an existing one.

Related

JPA query from java Object

How can i use jpa for query over an object (not an entity)?
For example this simple code:
String [] theList = {a,b,c,d}.
Query q = new Query("Select tl from theList tl")
Reason behind: the queries are dynamically created and executed, but the objects in the from clause of the jpql query aren't necessarily mapped tables. In some cases there are just an Object, So the actual behavior needed is modify the query during execution of the program to meet the criteria, but i don't know how to modify the query.
Edit: I Don't use native queries because of portability of code. It will be the last option.
What you're looking for is called LINQ, and unfortunately (?) it is available only in C#.
However, you can partially emulate it with Stream(s).
A Stream offers basically all the operators you need
.filter() where
.max() max
.sorted() orderby
.limit() limit
.skip() offset
.collect(groupingBy()) group by
And so on. Just give a look at the Javadoc!
I think 'JdbcTemplate' would suffice your requirement.
JdbcTemplate gives you the flexibility to run native queries and map them to a Java class.
However, you'll have to explicitly map your Java class with the column names in the database.
I have solved using joSQL. Is a powerfull opensource tool that allows you to query over java objects using "sql". It is not jpa but satisfied my needs.
Another tool i have seen that do that is called querydsl.

Having a Column name as Input Parameter of a PreparedStatement

I already used the search here (and other forums as well) but haven't found an answer exacty to what I'm trying to do.
I know that it can easily be done in some other way, and this is just a small sandbox-framework I'm coding for a University course... in a real environment I'd just take Spring, Hibernate etc.
So what I did was coding myself a small generic Data Access Layer with POJOs, working with generic methods to retrieve, check or insert data to the database (Oracle). Most of this is done through PreparedStatements.
This is working as long as I don't have joins... is it possible to put in a Column as parameter?
Example:
Table A has Attribute X + others
Table B has Attribute Y + others
PreparedStatement with query SELECT * FROM A,B WHERE "A"."X" = ?
And then fill in "B"."Y" as the parameter...
The database doesn't throw me an error or exception, but the ResultSet returned after executing the statement is empty. Is it just not possible to do, or am I just missing some escaping?
I'm using PreparedStatement.setString(int index, String value) to fill in the parameter... in lack of ideas which other setX method I could use...
Again, in a real project I'd never code that myself, but rather use something like Spring or Hibernate and not re-invent the wheel, but I see it as an interesting exercise to code such a generic small data access layer myself.
No, JDBC does not allow this. Only column values can be set. If you want to make dynamic changes to the sql statement you will have to do it before you create the PreparedStatement.

SQL table to nosql (MongoDB) - easy example

I have some problems to understand nosql. Im using mongodb and java and would like to create something like that: a table (persons) with a column for name (as string), age (as integer), married (boolean). In a normal sql it would be easy... but how to go on with mongodb and java?
Ok stuff I know: a table in mongodb is a collection and a column is a BSON field. I would start like this
Mongo m = new Mongo();
DB db = m.getDB("myDatabase");
DBCollection col = db.getCollection("Persons");
BasicDBObject doc = new BasicDBObject();
doc.put("something?", "something?");
col.insert(doc);
the first 3 steps are easy. I have my collection (table), I should make the BSON fields (columns) name, age, married. But how? I know the put() method, but what should I put in? And if I have the construct, I would like to add some "persons".
Any ideas? Thank you
You should try to get rid of thinking about columns with MongoDB. It is schemaless so every document may have different set of fields even in same collection so thinking fields are columns may be misleading.
I recommend going through the official MongoDB Java tutorial HERE.
You should be able to do something like this:
doc.put("name", "John");
doc.put("age", 30);
doc.put("married", false);
Taking a look at the documentation here:
http://api.mongodb.org/java/2.0/org/bson/BasicBSONObject.html#put(java.lang.String, java.lang.Object)
It seems to me that put accepts key and value for one of your fields, for instance:
doc.put("name", myPersonInstance.getName());
doc.put("age", myPersonInstance.getAge());
You can insert as many attributes using put as you want. There's also methods to add from a Map and such.
Please keep in mind I've never used the MongoDB Java API, so I'm basing my statements solely on that documentation and some slight knowledge of MongoDB in general.
For the record, those "put's" would be equivalent to a JSON structure like:
{name: "John", age:35}
Hope it helps.

Using sql column names in hibernate createSQlquery result

I have a couple of sql views with composite primary keys that I want to query, and since Hibernate makes it a pain to work with composite keyes, I'm using createSQLQuery. The problem is that this method can only return a List, and I need to refer to the colums by their index.
Any chance I could do something like jdbc and refer to the columns by their sql name instead of their index?
Query query=session.createSQLQuery("your query");
query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<Map<String,Object>> aliasToValueMapList=query.list();
As you can figure out from code, the list contains Map objects representing each row. Each Map object will have column name as key and value as value.
Note: This work for SQLQuery, if your using AliasToEntityMapResultTransformer on hql query without specifying aliases you will get index value as key.
If you are again transforming aliasToValueMapList to your POJO list, I advice you to create your own
ResultTransformer and return your custom object from 'transformTuple' method.
Your question is ambiguous - in the first paragraph you want to refer to columns by index and in the second, by sql name. Since by index is easy, I'll assume by name.
First of all, you can use the doWork method to access the underlying JDBC connection and handle it as you would with pure JDBC:
session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
connection.prepareStatement(...
}
});
Or, you can use query.getReturnAliases which returns a String[] of the column names. For effciency, I'd probably build a Map of alias to index and then you can do something like result[map.get("column name")].
But really, Hibernate handles composite keys pretty easily when using xml mappings (haven't tried with annotations). It's a little more work up front and there are a few issues with complex relationships (mainly when foreign key names/spans don't match), but once you create the id class and map it, you can stick with HQL/Criteria and get all the benefits of lazy loading, simple joins, dirty checking, etc.
I got the same problem but it solved when i used this
Query query=session.createSQLQuery("your query");
query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
I get the result with header name but i got a new problem when i create a new column in sql query Select 'DCA5E3' as Shipmentcolor from Employee.class
But in this case i got SHIPMENTCOLOR: "D".
How to get whole value of SHIPMENTCOLOR.

Wizard-generated JPA DAO method doesn't return an iterable List

I must be really stupid, but I'm at my wits' end with a JPA issue, using MyEclipse 7.5.
I am accessing a DB2 database (on an AS400) via JPA. I have reverse-engineered a simple table to provide a DAO with some precision "find" methods. So far so good.
If I run a SELECT statement over the table thus, I get 4 rows:
SELECT * FROM MyTable WHERE MyValue = '1234'
However, if I try to access these same 4 records via JPA, I get a list that's the right size (4), but which contains 4 objects which are all the same, all copies of the first object found:
List <MyTableObject> objects = dao.findByMyValue("1234");
It's almost as if the internal Query object that the DAO class creates can't iterate through the rows of data. I've tweaked the reveng.xml file myriad ways, and I've tinkered with the generated DAO, but I'm getting nowhere. Am I missing something really obvious here? I just want to get a list of objects in the same way that the conventional SELECT statement returns a resultset!
(This is MyEclipse 7.5, using Hibernate 3.2 and its associated JPA library).
UPDATE: here's the generated code that findByMyValue() passes over to (loggin / try-catch removed for clarity):
#SuppressWarnings("unchecked")
public List<PolicyStatFile> findByProperty(String propertyName, final Object value)
{
final String queryString = "select model from MyTableObject model where model." + propertyName + "= :propertyValue";
Query query = getEntityManager().createQuery(queryString);
query.setParameter("propertyValue", value);
return query.getResultList();
}
FINAL UPDATE
It was all about the model: see comments to this post. Essentially, the model generated from the reverse engineering file was invalid because I didn't have a truly unique key. Once I resolved this (spurred by comments here), all was well.
Method you've posted looks correct (although it seems rather pointless to generate this for all properties). Couple things to check:
Is MyValue property you've mentioned mapped directly on your entity (e.g. to the column on the same table; no associations are involved)?
Can you enable Hibernate SQL debug (set 'hibernate.show_sql' property to true in your configuration) and check what the generated query looks like?
Are 4 objects returned actually the same (e.g. are '==' to each other) or are they copies of each other (e.g. have the same property values)?
Can you post your mapping for the entity in question and generated SQL from #2 above?
I suspect you haven't overridden hashCode() and equals() in your JPA entity (e.g. MyTableObject). So Hibernate can't distinguish the returning rows. That a look here.

Categories