开发者

Connecting Java Object with MySql Tables

开发者 https://www.devze.com 2023-02-10 04:06 出处:网络
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.

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

  1. JBBC ResultSetMetaData
  2. Java Reflexion

But that's a harder work than using an existing one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号