Connecting Java Object with MySql Tables
I am working with Java Classes, and I'm looking for the easiest way to connect a DB table in MySQL with the me开发者_JAVA百科mbers (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.
精彩评论