1

我正在加载属于城市 235 的男性用户列表。好的,这很容易。但是现在如何加载属于城市 235 或 236 的男性用户列表?

BeanManager beanManager = new BeanManager();
User userProps = PropertiesProxy.create(User.class);
BeanConfig userConfig = new BeanConfig(User.class, "Users")
   .pk(userProps.getId(), DBTypes.AUTOINCREMENT)
   .field(userProps.getUsername(), DBTypes.STRING)
   .field(userProps.getGender(), DBTypes.ENUMID.from(Gender.class))
   .field(userProps.getCity().getId(), "city_id", DBTypes.INTEGER);
beanManager.addBeanConfig(userConfig);

BeanSession session = new MySQLBeanSession(beanManager, conn);
User u = new User();
u.setGender(Gender.MALE);
u.setCity(new City(235));

List<User> users = session.loadList(u, lim(250));

System.out.println("Found: " + users.size());

但现在我想在 where 子句中添加一个 OR 条件!我怎么做?

我正在使用这个框架

4

1 回答 1

1

使用任何 ORM,最终您都必须编写查询。就像具有分组依据、子查询、左连接等的查询一样,没有 SQL 就无法做你想做的事。有关示例,请参阅JOINS 。下面是您将如何进行查询:

PreparedStatement stmt = null;
ResultSet rset = null;

try {

    StringBuilder sql = new StringBuilder(1024);
    sql.append("select ");
    sql.append(session.buildSelect(User.class));
    sql.append(" from Users");
    sql.append(" where gender = ? and (city_id = ? or city_id = ?)");

    stmt = prepare(conn, sql.toString(), Gender.MALE.getId(), 235, 236); // varargs for params (from SQLUtils)

    rset = stmt.executeQuery();

    List<User> users = new LinkedList<User>();

    while(rset.next()) {
        User u = new User();
        session.populateBean(rset, u);
        users.add(u);
    }

    System.out.println("Number of users loaded: " + users.size());

} finally {
    close(rset, stmt, conn); // from SQLUtils
}

注意:您的代码中缺少性别列的映射,所以我假设它是一个ENUMID并且 Gender 枚举有一个 getId() 方法。否则,如果您使用 ENUMVALUE,请更改Gender.MALE.getId()Gender.MALE.toString().

于 2012-11-20T12:35:14.263 回答