【Java】JDBC Annotations (@Select)サンプル

ファイル名:
UserQueries.java

サンプルコード:
import java.sql.BaseQuery;
import java.sql.DataSet;
import java.sql.Select;

public interface UserQueries extends BaseQuery {
//すべてのユーザーを選択する
@Select (sql ="SELECT userId, firstName, lastName FROM Users",
readOnly=false, connected=false, tableName="Users")
DataSet<User> getAllUsers ();
// Select user by name */
@Select (sql ="SELECT userId, firstName, lastName FROM Users"
+ “WHERE userName=?", readOnly=false, connected=false,
tableName ="Users")
DataSet<User> getUserByName(String userName);

}

//処理プログラム

public void testQueryAnnotation( ) {
QueryAnnotationExample qae = null;
try {
String url = “jdbc:derby://localhost:1527/wrox;create=true";
Connection con = DriverManager.getConnection(url , “APP", “password");
qae = con.createQueryObject(QueryAnnotationExample.class);
} catch (SQLException e) {
e.printStackTrace();
}
Collection<Car> cars = qae.getCarsModelYear(“1999″);
for ( Car c : cars) {
System.out.println(" car id=" + c.getId() +
" model="+c.getModel() +" year="+ c.getYear() );
}
}

Development

Posted by arkgame