i am new to MyBatis,i am unable to find tutorials to learn,present i am going to start working on MyBatis with Spring,i had used session.selectOne(String arg0, Object arg1) but i am not able to understand how it works and what it will do with the second parameter that is Object arg1.
can any one help in this.
thank you
The second argument to selectOne and selectList is for a parameter. It can be a primitive if you have very simple needs in your query, say a single integer, or for more complicated queries requiring many values to be interpolated, a bean class instance with the values populated as needed (and containing the proper getters and setters).
In your mapper file you then define the type of the parameter via the parameter attribute, and can then interpolate either inline or with escaping (the former for things that should never be escaped, such as variable table or column names, and the latter for things which should always be escaped, such as values in a WHERE clause).
See the MyBatis doc for more detail:
http://mybatis.github.io/mybatis-3/java-api.html
Response to comments from OP:
MapBuilder must be custom code related to Map data structures. There's an ImmutableMap.Builder as part of Guava, but that doesn't seem like what this is. I don't think it's related to Mybatis per se.
It looks like that code is just building up a Map object, and then passing it off to the selectOne query for use within the query definition in the mapper (instead of a custom bean class).
What's the definition on LoginMapper.getUserByUsername in your mapper? In that definition, the contents of the map object are likely being interpolated into the query so dynamic values can be included.
Related
In GraphQL Java implementation's document, type wiring is done as below, which contains one for the human query and one for the friends field of the Human type as highlighted.
I am wondering what is the use of the latter, the one for the friends field of the Human type.
I think we already return the a whole Human object, including the friends field, in the former type wiring using the StarWarsData.getHumanDataFetcher(), then why we need the latter?
Thanks!
The schema is as below:
The friendsfield is of type Character[]. When you return a certain type, fields that aren't of a built-in scalar type (such as String, which is built-in, vs. Character which isn't) require their own fetcher in order to be retrieved. You can, however, define a DTO that models the Human type and the smart graphql.schema.PropertyDataFetcher provided by graphql-java should retrieve the fields of your POJO, since it knows how to follow POJO patterns based on the field name.
Is it possible to pass Java code as a value in a YAML file. For example, something like this:
---
dueDate: "DueDateCalc()"
DueDateCalc() might be a method defined in the Java code that is parsing the YAML. It would then set the Java dueDate property to the return of the predefined DueDateCalc() method.
This is possible within the constraints of Java runtime reflection, however you need to implement it yourself.
For example, your YAML could look like this:
---
dueDate: !call DueDateCalc
!call is a local tag for telling the loading code that the scalar value DueDateCalc should be interpreted as method to be called (this is chosen by you, not something predefined). You can implement this with a custom constructor for the !calc tag that searches for a method with the given name within some given class, and then calls it on some given object.
What about parameters? Well, still possible, but will get ugly fast. First problem is how you define the paramaters:
with nested YAML sequences: !call [MyMethod, [1, 2, 3]]
with a scalar that needs to be parsed: !call MyMethod(1, 2, 3)
The former option lets YAML parse the parameters and you'll get a list; the latter option requires you to parse the method call yourself from the string you get from YAML.
The second problem is to load the values into Java variables so that you can give them as argument list. Java reflection lets you get the method's parameter types and you can use those to load the parameter values. For example, if the first parameter's type is a String, you would parse 1 as a "1", while if it's an int, you can parse 1 as int. This is possible with SnakeYAML's builtin facilities if you're using nested YAML sequences for method call encoding.
This would even work if parameters are class objects with complex structure, you'd just use normal YAML syntax and the objects will be loaded properly. Referring to variables in your code is not directly possible, but you could define another tag !lookup which retrieves values from a given Map structure.
While reflection lets you make method calls, you can not directly evaluate an expression like 6*9. So before you try and implement anything, evaluate which functionality you need and check whether it's doable via reflection.
I created a method which through spring data automatically create the query. The problem is about the return param, because dismatch from the name definition.
In fact by specifying only one parameter, it return 4 parameters.
The springData method is that:
Optional<Comunicazioni> getCommIDByExtIDAndCommSAndCommT(
BigDecimal extID, String commS, String commT);
and I access to the type like so:
getCommIDByExtIDAndCommSAndCommT(extId, commS, commT).get().getCommID()
how can I retrieve only the column I need?
Thank you
Unfortunately, this is not possible with the current implementation of Spring Data JPA (i.e. Using method name only).
Instead, the current solution is to use #Query to define the return values. You can find an example of that here.
However, if your Entity object is not too large, you would be able to achieve the result in the example you posted by simply retrieving the entire entity:
Optional<Comunicazioni> findByExtIDAndCommSAndCommT(BigDecimal extID, String commS, String commT);
and then calling it as
repo.findByExtIDAndCommSAndCommT(extId, commS, commT).get().getCommID();
It would be nice to see this functionality in the future, but for now, it is not so difficult to work around.
in hibernate to create criteria we use
Criteria criterea=session.createCritera(SomeClass.class)
It may be available in some other examples too but I am not able to understand the structure of these type of methods.
NOTE this is an example I am trying to put to understand use of SomeClass.class like arguments
my question here is what is purpose of SomeClass.class ? why do we need it, what is the advantages of using it as argument.
Edit its not a duplicate but have string connection to this question
What is this .class syntax?
If you attach .class to the end of a class name, you get the Class<T> object corresponding to the class.
Examples:
String.class returns an instance of Class<String>
Integer.class returns an instance of Class<Integer>
What can you do with a class object
Reflection! If you have access to a class object, you can do all kinds of cool stuff! You can call methods, get and set values of fields...
Why is this used in Hibernate?
I haven't used hibernate before, but this syntax is used in other libraries as well, especially in ORMs or JSON serializers. I'll use JSON serializers as an example as I'm more familiar with those.
In a JSON serializer, you need to give it a class object because it needs to get all the fields that you want to serialize to JSON. It uses reflection to get and set the values of those fields, then convert them to JSON. When it deserializes JSON, it finds the field that needs to be set with the name in the JSON. These operations require a Class object because without it, how can Java know which class should it find the field? Also, to create a new object with reflection, a Class is needed as well!
Hibernate provides many ways to handle the objects in relation with RDBMS tables.
One way is Session interface providing createCriteria() method which can be used to create a Criteria object.
As name says criteria, it is useful to execute queries by applying filtration rules and logical conditions of programmer wish.
For example:
Criteria obj=session.createCritera(Galaxy.class) // say SomeClass is Galaxy.class
List results = obj.list();
Here, criteria query is one which will simply return every object that corresponds to the Galaxy class.
We even can restrict the results with criteria, example add() method available for Criteria object to add restriction for a criteria query.
Following is the restriction to return the records with planet which has 7.4 billion population from Galaxy class:
Criteria cr = session.createCriteria(Galaxy.class);
cr.add(Restrictions.eq(“planet”, 75000000000));
List results = cr.list();
I'm developing a framework in java which relies on a number of XML files with large number of parameters.
When reading the parameters from the XML file, I have to have a large if-else statement to decide what the parameters is and then call appropriate methods.
Is this normal? to have a large if-else statement?
I am thinking that there is a simple and neater way of doing this, e.g. Java XML mapping or Java Reflections? is this the answer? if so, can you please provide examples of how this is done so I don't have to rely on a large if-else statement?
Thanks!
You want to first create an interface:
public interface XMLParameterHandler {
public handle_parameter (String XMLData);
}
Next you want to create a map:
private Map<string, XMLParameterHandler> handlers;
...and initialize it with one of the relevant Map implementations:
this.handlers = new HashMap<>();
You need to implement the interface on a number of classes, one for each parameter you intend to handle. This is a good use of inner classes. Insert each of these implemented handerls into the map:
handlers.put ("Param1", new XMLParam1HandlerImpl());
handlers.put ("Param2", new XMLParam2HandlerImpl());
Then you can call the handler from the xml processing loop:
handlers.get (paramValue).handle_parameter(XmlData);
There is JAXB (http://en.wikipedia.org/wiki/Java_Architecture_for_XML_Binding) for mapping java class to xml.
But you can't map methods with it: you only can map attributes to xml file values (deserialize parameters from xml).
i recommend to use Map, that have parameter as key and xml entry as value(not whole xml)
Reflection would be one approach. Perhaps combined with a custom annotation on the target method to indicate which parameter to pass to that method. This is an advanced technique, though.
A more standard technique would be to use a map, where the key is the attribute name, and the value is an instance of an implementation of some interface you define, like AttributeHandler. The implementations then contain the code for each attribute. This involves writing a lot of little classes, but you can do them as anonymous classes to save space and keep the code inline.
a large if-else statement to decide what the parameters is and then call appropriate methods
You could instead use the Strategy design pattern, with one Strategy object per parameter, and use a map from the parameter name to the Strategy object to use. I've found this approach useful for even a moderately complicated application of XML.
It sounds to me as if you want a data-driven rule-based approach to writing your application, rather like you get in XSLT. One way of achieving this is to write it in XSLT instead of Java - XSLT, after all, was specifically designed for processing XML, while Java wasn't. If you can't do that, you could study how XSLT does it using rules and actions, and emulate this design in your Java code.
N functions with M parameters can always be implemented with a single function with M + 1 parameters.
If you need a big if then else statement to decide which method to dispatch to, then you can just add a parameter to your method and call a single method.
You shouldn't need an if-then-else statement to bind the parameter values.
If there is complex logic dependent on the particular parameter values, you might use a table driven approach. You can map various combinations of paramemter values into equivalence classes, then variouos equivalence class combinations into a row in a table with a unique id, then have a switch statement based on that unique id.