返回顶部

收藏

JDBC Annotations (@Select) 示例

更多

java.sql.Select 是 JDK 6 和 JDBC 4 中新增的 Annotation

UserQueries.java

import java.sql.BaseQuery;
import java.sql.DataSet;
import java.sql.Select;

public interface UserQueries extends BaseQuery {

    // Select all users
    @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() );
  }
  }

标签:JDBC,Annotation

收藏

0人收藏

支持

0

反对

0

发表评论