简体   繁体   中英

How do I execute queries in Play framework (with Oracle 10g)

I did this JDBC code for fetching some data from the database Oracle 10g using Play Framework 1.2.5:

Connection conn = DB.getConnection();
PreparedStatement  stmt = null;
System.out.println(conn);
try {
    stmt = conn.prepareStatement("select dept_id from emp where emp_id = 11");
    ResultSet rs = stmt.executeQuery();
    while (rs.next()) {
        System.out.println("Dept Id: " + rs.getInt("dept_id"));
    }
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

This approach is working but I am having a confusion:

If I comment the entire block of code and run the application then I can see the message in the console stating the connection is made to the DB. Hence :

1) Is the above block of code the right approach to fetch the data from Oracle DB or something better than this is present?

2) Is it like for the entire application lifetime, the connection with tht DB will persist?

I am a newbie in this, hence struggling :(

Please let me know hoe to proceed with this.

Regards

You need to read the play JPA documentation: http://www.playframework.org/documentation/1.2.5/jpa#finding

Your queries should look like this:

Post.find("byTitle", "My first post").fetch();
Post.find("byTitleLike", "%hello%").fetch();
Post.find("byAuthorIsNull").fetch();
Post.find("byTitleLikeAndAuthor", "%hello%", connectedUser).fetch();

And if you need to do a full query, you can add the JPA code in find:

Post.find(
    "select p from Post p, Comment c " +
    "where c.post = p and c.subject like ?", "%hop%"
);

1) Your code is okay, as long as you close the ResultSet, PreparedStatement and Connection objects when you're done using them (close() method!). Essentially, you are running a "native query", as opposed to the JPA/ORM approach recommended by Tom. Both have their advantages, I suggest you learn about JPA and see which one suits your needs best.

There is another option for native queries in Play with less boilerplate code: JPA.em().createNativeQuery().

2) DB.getConnection() will probably translate into a call to a connection pool, if so, you don't need to worry about the lifetime of the connection, just make sure to "give it back" to the pool when you no longer need it, ie close() all the objects I mentioned above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM