我查看了某人编写的代码,因为无法获得结果。代码不正确,但至少我希望public Language getLanguageByCode(String code) {
Criteria criteria = getSession().createCriteria(Language.class);
if (code.length() == 3)
criteria = criteria.add(Restrictions.eq("threeCode", code.toUpperCase()));
else if (code.length() == 2)
criteria = criteria.add(Restrictions.eq("twoCode", code.toUpperCase()));
else {
throw new RuntimeException("code incorrect");
}
criteria = criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
@SuppressWarnings("unchecked")
List<Language> langList = criteria.list();
Language lang = null;
if (langList.size() > 1) {
LOG.error("Query result size is bigger than expected!");
lang = (Language) criteria.list().get(0);
} else if (langList.size() == 1) {
criteria.setFirstResult(0);
criteria.setMaxResults(1);
lang = (Language) criteria.uniqueResult();
}
return lang;
}
从数据库返回结果。在同一数据库上运行生成的SQL查询或按以下方式更正代码时,会得到结果。
我想了解为什么没有得到结果
代码不正确
select
this_.id as id23_0_,
this_.three_code as three2_23_0_,
this_.title as title23_0_,
this_.two_code as two4_23_0_
from
language this_
where
this_.two_code=?
2019-06-12 16:12:15 TRACE BasicBinder:83 - binding parameter [1] as [VARCHAR] - EN
Hibernate生成的查询:
public Language getLanguageByCode(String code) {
Criteria criteria = getSession().createCriteria(Language.class);
if (code.length() == 3)
criteria = criteria.add(Restrictions.eq("threeCode", code.toUpperCase()));
else if (code.length() == 2)
criteria = criteria.add(Restrictions.eq("twoCode", code.toUpperCase()));
else {
throw new RuntimeException("code incorrect");
}
criteria = criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
@SuppressWarnings("unchecked")
List<Language> langList = criteria.list();
if (langList.size() == 0)
return null;
if (langList.size() > 1)
LOG.error("Query result size is bigger than expected!");
return langList.get(0);
}
正确的密码
public class SqlManager{
private AsyncSQLClient _sqlClient;
public SqlManager(MySqlHelper sqlHelper, SqlSettings settings) {
ConnectionConfig config = new ConnectionConfig(settings.Address, settings.Port,
settings.Database, settings.User, settings.Password);
_sqlClient = sqlHelper.getSqlConnection(config);
}
}
public class MySqlHelper {
private Vertx _vertx;
public MySqlHelper(Vertx vertx) {
_vertx = vertx;
}
public AsyncSQLClient getSqlConnection(ConnectionConfig config) {
AsyncSQLClient sqlClient = MySQLClient.createNonShared(_vertx, config.get());
return sqlClient;
}
}