mybatis- 3.1.1. how to override the resultmap returned from mybatis - ibatis

we using mybatis 3.1.1.
we found for oracle the result map returned contains column name in Capital letters and in case of mySql the result map returned contains column name in small letters.
My question is : Is there is any way i can to write some sort of interceptor so that i can modify the result returned by result map.
Thanks.

I'm afraid the answer is that MyBatis doesn't provide any direct way to control the case of the keys in a result map. I asked this question recently on the MyBatis Google Group: https://groups.google.com/forum/?fromgroups#!topic/mybatis-user/tETs_JiugNE
The outcome is dependent on the behavior of the JBDC driver.
It also turns out that doing column aliasing as suggested by #jddsantaella doesn't work in all cases. I've tested MyBatis-3.1.1 with three databases in the past: MySQL, PostgreSQL and H2 and got different answers. With MySQL, the case of the column alias does dictate the case of the key in the hashmap. But with PostgreSQL it is always lowercase and with H2, it is always uppercase. I didn't test whether column aliases will work with Oracle, but by default it appears to return capital letters.
I see two options:
Option 1: Create some helper method that your code will always use to pull the data out of the returned map. For example:
private Object getFromMap(Map<String, Object> map, String key) {
if (map.containsKey(key.toLowerCase())) {
return map.get(key.toLowerCase());
} else {
return map.get(key.toUpperCase());
}
}
Option 2: Write a LowerCaseMap class that extends from java.util.AbstractMap or java.util.HashMap and wrappers all calls to put, putAll and/or get to always be lower case. Then specify that MyBatis should use your specific LowerCaseMap rather than a standard HashMap, when populating the data from the query.
If you like this idea and want help on how to tell MyBatis how to use a different concrete collection class, see my answer to this StackOverflow question: https://stackoverflow.com/a/11596014/871012

What if you modify the query so you get the exactly column name you need? For example:
select my_column as MY_COLUMN from ...

The idea of a LowerCaseMap as the ResultType is sound, but you can probably avoid writing your own. In my case I'm using org.apache.commons.collections4.map.CaseInsensitiveMap:
<select id="getTableValues"
resultType="org.apache.commons.collections.map.CaseInsensitiveMap">
SELECT *
FROM my_table
WHERE seq_val=#{seq_val}
</select>

Related

MS Access, use query name as field default value

My department uses a software tool that can use a custom component library sourced from Tables or Queries in an MS Access database.
Table: Components
ID: AutoNumber
Type: String
Mfg: String
P/N: String
...
Query: Resistors
SELECT Components.*
FROM Components
WHERE Components.Type = "Resistors"
Query: Capacitors
SELECT Components.*
FROM Components
WHERE Components.Type = "Capacitors"
These queries work fine for SELECT. But when users add a row to the query, how can I ensure the correct value is saved to the Type field?
Edit #2:
Nope, can't be done. Sorry.
Edit #1:
As was pointed out, I may have misunderstood the question. It's not a wonky question after all, but perhaps an easy one?
If you're asking how to add records to your table while making sure that, for example, "the record shows up in a Resistors query if it's a Resistor", then it's a regular append query, that specifies Resisitors as your Type.
For example:
INSERT INTO Components ( ID, Type, Mfg )
SELECT 123, 'Resistors', 'Company XYZ'
If you've already tried that and are having problems, it could be because you are using a Reserved Word as a field name which, although it may work sometimes, can cause problems in unexpected ways.
Type is a word that Access, SQL and VBA all use for a specific purpose. It's the same idea as if you used SELECT and FROM as field or table names. (SELECT SELECT FROM FROM).
Here is a list of reserved words that should generally be avoided. (I realize it's labelled Access 2007 but the list is very similar, and it's surprisingly difficult to find an recent 'official' list for Excel VBA.)
Original Answer:
That's kind a a wonky way to do things. The point of databases is to organize in such a way as to prevent duplication of not only data, but queries and codes as well
I made up the programming rule for my own use "If you're doing anything more than once, you're doing it wrong." (That's not true in all cases but a general rule of thumb nonetheless.)
Are the only options "Resistors" and "Capacitors"? (...I hope you're not tracking the inventory of an electronics supply store...) If there are may options, that's even more reason to find an alternative method.
To answer your question, in the Query Design window, it is not possible to return the name of the open query.
Some alternative options:
As #Erik suggested, constrain to a control on a form. Perhaps have a drop-down or option buttons which the user can select the relevant type. Then your query would look like:
SELECT * FROM Components WHERE Type = 'Forms![YourFormName]![NameOfYourControl]'
In VBA, have the query refer to the value of a variable, foe example:
Dim TypeToDel as String
TypeToDel = "Resistor"
DoCmd.RunSQL "SELECT * FROM Components WHERE Type = '" & typeToDel'"
Not recommended, but you could have the user manually enter the criteria. If your query is like this:
SELECT * FROM Components WHERE Type = '[Enter the component type]'
...then each time the query is run, it will prompt:
Similarly, you could have the query prompt for an option, perhaps a single-digit or a code, and have the query choose the the appropriate criteria:
...and have an IF statement in the query criteria.
SELECT *
FROM Components
WHERE Type = IIf([Enter 1 for Resistors, 2 for Capacitors, 3 for sharks with frickin' laser beams attached to their heads]=1,'Resistors',IIf([Enter 1 for Resistors, 2 for Capacitors, 3 for sharks with frickin' laser beams attached to their heads]=2,'Capacitors','LaserSharks'));
Note that if you're going to have more than 2 options, you'll need to have the parameter box more than once, and they must be spelled identically.
Lastly, if you're still going to take the route of a separate query for each component type, as long as you're making separate queries anyway, why not just put a static value in each one (just like your example):
SELECT * FROM Components WHERE Type = 'Resistor'
There's another wonky answer here but that's just creating even more duplicate information (and more future mistakes).
Side note: Type is a reserved word in Access & VBA; you might be best to choose another. (I usually prefix with a related letter like cType.)
More Information:
Use parameters in queries, forms, and reports
Use parameters to ask for input when running a query
Microsoft Access Tips & Tricks: Parameter Queries
 • Frickin' Lasers

Can I find such a intelligent function to deal with all query conditions in database

If we want to query something in database, we can use where conditions, such as select * from user where id=1;
I can define a function :
bool query(int id,string tableName)
{
database.id.equalTo(id);
}
if I want to find the user less than 18(age) years old:
bool query(int age,string tableName)
{
database.age.lessthan(age);
}
so for two conditions we have two function relative.
Can I find such a way ,that
bool query(string condition)
{
database.find(condition);
//it will deal with the condition intelligent use the required function.
}
I know database can read sql syntax. But I want to find the function that can provide developer a convenient way without writing the sql syntax, just pass the condition sentence that: age<18, id=1. And the function return the result1.When enter arg>19 the function return the result2.
I am not sure if I have mention my problem clearly. Seeking for help!
For PHP you can use Doctrine ORM. Doctrine 2 is an object-relational mapper (ORM) for PHP 5.4+ that provides transparent persistence for PHP objects.
The 'where' clause should do what you need.
http://doctrine-orm.readthedocs.org/en/latest/reference/query-builder.html#high-level-api-methods
Similar QueryBuilders exist in other languages. No need to reinvent the wheel.
http://doctrine-orm.readthedocs.org/en/latest/tutorials/getting-started.html

Rails 3, ActiveRecord, PostgreSQL - ".uniq" command doesn't work?

I have following query:
Article.joins(:themes => [:users]).where(["articles.user_id != ?", current_user.id]).order("Random()").limit(15).uniq
and gives me the error
PG::Error: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...s"."user_id" WHERE (articles.user_id != 1) ORDER BY Random() L...
When I update the original query to
Article.joins(:themes => [:users]).where(["articles.user_id != ?", current_user.id]).order("Random()").limit(15)#.uniq
so the error is gone... In MySQL .uniq works, in PostgreSQL not. Exist any alternative?
As the error states for SELECT DISTINCT, ORDER BY expressions must appear in select list.
Therefore, you must explicitly select for the clause you are ordering by.
Here is an example, it is similar to your case but generalize a bit.
Article.select('articles.*, RANDOM()')
.joins(:users)
.where(:column => 'whatever')
.order('Random()')
.uniq
.limit(15)
So, explicitly include your ORDER BY clause (in this case RANDOM()) using .select(). As shown above, in order for your query to return the Article attributes, you must explicitly select them also.
I hope this helps; good luck
Just to enrich the thread with more examples, in case you have nested relations in the query, you can try with the following statement.
Person.find(params[:id]).cars.select('cars.*, lower(cars.name)').order("lower(cars.name) ASC")
In the given example, you're asking all the cars for a given person, ordered by model name (Audi, Ferrari, Porsche)
I don't think this is a better way, but may help to address this kind of situation thinking in objects and collections, instead of a relational (Database) way.
Thanks!
I assume that the .uniq method is translated to a DISTINCT clause on the SQL. PostgreSQL is picky (pickier than MySQL) -- all fields in the select list when using DISTINCT must be present in the ORDER_BY (and GROUP_BY) clauses.
It's a little unclear what you are attempting to do (a random ordering?). In addition to posting the full SQL sent, if you could explain your objective, that might be helpful in finding an alternative.
I just upgraded my 100% working and tested application from 3.1.1 to 3.2.7 and now have this same PG::Error.
I am using Cancan...
#users = User.accessible_by(current_ability).order('lname asc').uniq
Removing the .uniq solves the problem and it was not necessary anyway for this simple query.
Still looking through the change notes between 3.1.1 and 3.2.7 to see what caused this to break.

Mongoid Syntax Questions

1) Finding by instance object
Assuming I have the instance object called #topic. I want to retrieve the answers for this given topic. I was thinking I should be able to pass in :topics=>#topic, but i had to do the very ugly query below.
#answers = Answers.where(:topic_ids => {"$in" => [#topic.id]})
2) Getting the string representation of the id. I have a custom function (shown below). But shouldn't this be a very common requirement?
def sid
return id.to_s
end
If your associations are set up correctly, you should be able to do:
#topic.answers
It sounds like the above is what you are looking for. Make sure you have set up your associations correctly. Mongoid is very forgiving when defining associations, so it can seem that they are set up right when there is in fact a problem like mismatched names in references_many and referenced_in.
If there's a good reason why the above doesn't work and you have to use a query, you can use this simple query:
#answers = Answer.where(:topic_ids => #topic.id)
This will match any Answer record whose topic_ids include the supplied ID. The syntax is the same for array fields as for single-value fields like Answer.where(:title => 'Foo'). MongoDB will interpret the query differently depending on whether the field is an array (check if supplied value is in the array) or a single value (check if the supplied value is a match).
Here's a little more info on how MongoDB handles array queries:
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray

Grails multi column indexes

Can someone explain how to define multi column indexes in Grails? The documentation is at best sparse.
This for example does not seem to work at all:
http://grails.org/GORM+Index+definitions
I've had some luck with this, but the results seems random at best. Definitions that works in one domain class does not when applied to another (with different names of course).
http://www.grails.org/doc/1.1/guide/single.html#5.5.2.6%20Database%20Indices
Some working examples and explanations would be highly appreciated!
The solution that has worked for me for multi-column indexes is:
class ClassName {
String name
String description
String state
static mapping = {
name index: 'name_idx'
description index: 'name_idx'
state index: 'name_idx'
}
}
This creates an index called 'name_idx' with the three columns in the index.
Downside: the columns are listed in the index in alphabetical order, not the order that they were entered.
To make your index multi-column, list the columns with comma separator (note, no space after the comma, to avoid this bug. The second URL you point to hits the bug, as it says:
index:'Name_Idx, Address_Index'
with a space; it should work as
index:'Name_Idx,Address_Index'
The first URL you point to was a proposed change (I don't believe it's implemented currently and have no idea how likely it is to ever be).
AFAIK, the index closure shown here was never implemented, so those examples should be ignored (this page is for discussing possible implementations, rather than documenting an actual implementation).
The correct way to define a single-column index name_idx for a name property is
static mapping = {
name index:'name_idx'
}
Sorry, but I don't know how to define a multi-column index, try the Grails mailing list if you don't get an answer here. In the unlikely event that multi-column indices can't be declared directly in the domain classes, you could define them in an SQL file which creates them if they don't already exist (or drops and re-creates them). This SQL file could be executed by the init closure in Bootstrap.groovy
I needed to be able to control the order of the columns in my multi-column index and also make it unique. I worked around the GORM / Hibernate limitations by creating the index in Bootstrap using direct SQL:
class BootStrap {
DataSource dataSource
def init = { servletContext ->
if (!MyModel.count()) { // new database
createIndexes()
...
}
}
private void createIndexes() {
Sql sql = new Sql(dataSource)
sql.execute("create unique index my_index on my_model(col1,col2);")
}

Resources