EclipseLink (JPA 2) Missing Descriptor Exception - native

I am having an issue using EclipseLink (JPA 2) in Netbeans 6.9.1 against Oracle 11g. I keep getting the following error when attempting to run a Native Query:
Exception Description: Missing descriptor for [class Novartis.OTM.Data.Db.Entities.Lookup].
Query: ReadAllQuery(referenceClass=Lookup sql="SELECT l FROM lookup l WHERE l.lookup_type = :LookupType AND domain = :Domain")
He's the code:
public List<SelectItem> getLookupForUI(enumLookupType lookupType, String domain) throws Exception {
if (domain == null || domain.trim().equals(""))
throw new Exception("Parameter domain cannot be null or empty.");
else if (!this.isInitialized())
throw new Exception("Entity Manager not set.");
Query query = this._EM.createNativeQuery(_QueryGetLookupForUI, Lookup.class);
query.setParameter("LookupType", lookupType.toString());
query.setParameter("Domain", domain.trim());
List<SelectItem> selectItems = null;
List<Lookup> lookupList = (List<Lookup>) query.getResultList();
if (lookupList == null || lookupList.size() < 1)
return null;
else {
selectItems = new ArrayList<SelectItem>(lookupList.size());
for (Lookup lookUp : lookupList) {
selectItems.add(new SelectItem(lookUp.getLookupValue(), lookUp.getLookupName()));
}
}
return selectItems;
}
Despite checking that I have a valid entity class, I don't know why this is failing. Thank you in advance for your assistance.
Chris

Maybe try:
SELECT l FROM Lookup instead of SELECT l FROM lookup?

Related

Apache Calcite | HSQLDB - Table Not Found Exception

I am trying to learn Apache Calcite by following the RelBuilderExample with the storage layer being HSQLDB.
Unfortunately, I keep getting "Table Not Found exception" when i call builder.scan(tableName) API of Apache Calcite. When I query the data in HSQL directly using ResultSet rs = statement.executeQuery("SELECT * from file"); then i am able to retrieve the data. Here is the relevant code:
//I create an instance of RelBuilder using the Config defined below
RelBuilder builder = RelBuilder.create(config().build());
//This line throws me exception: org.apache.calcite.runtime.CalciteException: Table 'file' not found
builder = builder.scan("file");
/**
Building the configuration backed by HSQLDB
*/
public static Frameworks.ConfigBuilder config() throws Exception{
//Getting the ConnectionSpec for the in memory HSQLDB
//FileHSQLDB.URI = "jdbc:hsqldb:mem:intel"
//FileHSQLDB.USER = "user"
//FileHSQLDB.PASSWORD = "password"
final ConnectionSpec cs = new ConnectionSpec(FileHSQLDB.URI, FileHSQLDB.USER, FileHSQLDB.PASSWORD, "org.hsqldb.jdbcDriver", "intel");
//cs.url = "jdbc:hsqldb:mem:intel"
//cs.driver = "org.hsqldb.jdbcDriver"
//cs.username = "user"
//cs.password = "password"
DataSource dataSource = JdbcSchema.dataSource(cs.url, cs.driver, cs.username, cs.password);
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
//This returns me 3 results
ResultSet rs = statement.executeQuery("SELECT * from file");
while(rs.next()) {
String id = rs.getString("file_id");
System.out.println(id);
}
// Next I create the rootSchema
SchemaPlus rootSchema = Frameworks.createRootSchema(true);
//I suspect that there is some issue in the below line. I think I
//am not using Apache Calcite APIs properly, but not sure what I
//am doing wrong.
rootSchema.add("intel", JdbcSchema.create(rootSchema, "intel", dataSource, cs.catalog, cs.schema));
return Frameworks.newConfigBuilder().defaultSchema(rootSchema);
Can someone please help me what I may be doing wrong.
If your table is file (lowercase) then make sure you quote the table name in the query, i.e. "SELECT * from \"file\"".

How to get the ID of inserted row in JDBC with old driver?

I want to get auto increment id of inserted row. I know that there is a lot of examples how to do that:
link1
link2
But I use HSQL 1.8.0.10 and following code:
PreparedStatement ps = conn.prepareStatement("insert into dupa (v1) values(3)", Statement.RETURN_GENERATED_KEYS);
throws expection:
java.sql.SQLException: This function is not supported
How to get id if driver does not support the above solution. Is any other way to get auto increment key of inserted row? I want to handle as much as possible drivers. So want to use obove code in try section and use another way in catch section.
Second question: Is possible that database does not support this feature. So even if I use new driver and old database It will still not work? I tried to use hsql 2.3.2 driver but I can not to connect to 1.8.0.10 database.
The following code illustrates how to retrieve generated keys from HSQLDB 2.2.9 and later using the included JDBC 4 driver. This method returns a two element long[]. The first element contains the number of rows that were updated; the second contains the generated key if any:
static final long[] doUpdate( ... ) {
final long[] k = new long[] {0, KEY_UNDEFINED};
PreparedStatement ps = null;
try {
ps = CXN.get().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
JdbcValue jv;
for (int i = 0; i < data.size(); i++) {
jv = data.get(i);
jv.type().setJdbcParameter(i + 1, ps, jv);
}
k[NUM_OF_ROWS] = (long) ps.executeUpdate();
if (k[NUM_OF_ROWS] > 0L) {
try (ResultSet rs = ps.getGeneratedKeys()) {
final String identColName = idCol.colName();
while (rs.next()) {
if (k[ROW_CREATED] != KEY_UNDEFINED) throw new AssertionError();
k[ROW_CREATED] = rs.getLong(identColName);
}
}
}
} catch (SQLException e) { ... }
finally {
try { if (ps != null) ps.close(); } catch (SQLException e) { }
}
return k;
}
I am unable to say whether this approach will work with old versions of HSQLDB.
You will have to use some vendor-specific solution, i.e. in mysql you would call LAST_INSERT_ID function.
I don't have valid installation of HSQL to test it, but you can give a try to the highest voted solution from this topic: how to return last inserted (auto incremented) row id in HSQL?

Dapper.Net and the DataReader

I have a very strange error with dapper:
there is already an open DataReader associated with this Command
which must be closed first
But I don't use DataReader! I just call select query on my server application and take first result:
//How I run query:
public static T SelectVersion(IDbTransaction transaction = null)
{
return DbHelper.DataBase.Connection.Query<T>("SELECT * FROM [VersionLog] WHERE [Version] = (SELECT MAX([Version]) FROM [VersionLog])", null, transaction, commandTimeout: DbHelper.CommandTimeout).FirstOrDefault();
}
//And how I call this method:
public Response Upload(CommitRequest message) //It is calling on server from client
{
//Prepearing data from CommitRequest
using (var tr = DbHelper.DataBase.Connection.BeginTransaction(IsolationLevel.Serializable))
{
int v = SelectQueries<VersionLog>.SelectVersion(tr) != null ? SelectQueries<VersionLog>.SelectVersion(tr).Version : 0; //Call my query here
int newVersion = v + 1; //update version
//Saving changes from CommitRequest to db
//Updated version saving to base too, maybe it is problem?
return new Response
{
Message = String.Empty,
ServerBaseVersion = versionLog.Version,
};
}
}
}
And most sadly that this exception appearing in random time, I think what problem in concurrent access to server from two clients.
Please help.
This some times happens if the model and database schema are not matching and an exception is being raised inside Dapper.
If you really want to get into this, best way is to include dapper source in your project and debug.

Column is not indexed even though it is. PreparedStatement inside

I'm really struggling with a bug that did not appear on my dev environment, only once deployed in test.
I'm using a prepared Statement to run around 30 000 query in a row. The query check for the similarity of a string with what's in our database, using the oracle fuzzy method.
The column checked is indexed, but, don't know why, it fails randomly after some iterations, saying that index does not exists.
I don't understand what's going on, as the index really exists. My method never rebuild or delete the index so there is no reason for this error to appear ...
public List<EntryToCheck> checkEntriesOnSuspiciousElement(List<EntryToCheck> entries, int type,int score, int numresults, int percentage) throws Exception {
Connection connection = null;
PreparedStatement statementFirstName = null;
PreparedStatement statementLastname = null;
int finalScore = checkScore(score);
int finalNumResults = checkNumResults(numresults);
int finalPercentage = checkPercentage(percentage);
try {
connection = dataSource.getConnection();
StringBuilder requestLastNameOnly = new StringBuilder("SELECT SE.ELEMENT_ID, SE.LASTNAME||' '||SE.FIRSTNAME AS ELEMENT, SCORE(1) AS SCORE ");
requestLastNameOnly.append("FROM BL_SUSPICIOUS_ELEMENT SE ");
requestLastNameOnly.append("WHERE CONTAINS(SE.LASTNAME, 'fuzzy({' || ? || '},' || ? || ',' || ? || ', weight)', 1)>? ");
requestLastNameOnly.append((type > 0 ? "AND SE.ELEMENT_TYPE_ID = ? " : " "));
requestLastNameOnly.append("ORDER BY SCORE DESC");
statementLastname = connection.prepareStatement(requestLastNameOnly.toString());
for (EntryToCheck entryToCheck : entries) {
ResultSet rs;
boolean withFirstName = (entryToCheck.getEntryFirstname() != null && !entryToCheck.getEntryFirstname().equals(""));
statementLastname.setString(1, entryToCheck.getEntryLastname().replaceAll("'","''"));
statementLastname.setInt(2, finalScore);
statementLastname.setInt(3, finalNumResults);
statementLastname.setInt(4, finalPercentage);
if(type > 0){
statementLastname.setInt(5, type);
}
System.out.println("Query LastName : " + entryToCheck.getEntryLastname().replaceAll("'","''") );
rs = statementLastname.executeQuery();
while (rs.next()) {
Alert alert = new Alert();
alert.setEntryToCheck(entryToCheck);
alert.setAlertStatus(new AlertStatus(new Integer(AlertStatusId.NEW)));
alert.setAlertDate(new Date());
alert.setBlSuspiciousElement(new BlSuspiciousElement(new Integer(rs.getInt("ELEMENT_ID"))));
alert.setMatching(rs.getString("ELEMENT") + " (" + rs.getInt("SCORE") + "%)");
entryToCheck.addAlert(alert);
}
}
}
catch (Exception e) {
e.printStackTrace();
throw e;
}
finally {
DAOUtils.closeConnection(connection, statementLastname);
}
return entries;
}
Really don't know what to look at ...
Thanks !
F
I never used Oracle text tables but my advice is:
Make sure that no one else is executing DDL statements on the table simultaneously.
Also, make sure that, index you have is context index.
Create an index for your column where you want to apply search
........................................
CREATE INDEX "MTU219"."SEARCHFILTER" ON "BL_SUSPICIOUS_ELEMENT " ("LASTNAME")
INDEXTYPE IS "CTXSYS"."CONTEXT" PARAMETERS ('storage CTXSYS.ST_MTED_NORMAL SYNC(ON COMMIT)');
..........................................

nhibernate hql with named parameter

I have implemented a search function using Castel Active Record. I thought the code is simple enough but I kept getting
NHibernate.QueryParameterException : could not locate named parameter [searchKeyWords]
errors. Can someone tell me what went wrong? Thanks a million.
public List<Seller> GetSellersWithEmail(string searchKeyWords)
{
if (string.IsNullOrEmpty(searchKeyWords))
{
return new List<Seller>();
}
string hql = #"select distinct s
from Seller s
where s.Deleted = false
and ( s.Email like '%:searchKeyWords%')";
SimpleQuery<Seller> q = new SimpleQuery<Seller>(hql);
q.SetParameter("searchKeyWords", searchKeyWords);
return q.Execute().ToList();
}
Why do not u pass the % character with parameter?
string hql = #"select distinct s
from Seller s
where s.Deleted = false
and ( s.Email like :searchKeyWords)";
SimpleQuery<Seller> q = new SimpleQuery<Seller>(hql);
q.SetParameter("searchKeyWords", "%"+searchKeyWords+"%");
return q.Execute().ToList();