MyBatis 3.1.1, how to execute custom SQL code directly - java

I use PostrgeSQL 9.6 and MyBatis 3.1 (under there is also Java 8 and Spring), and I need to execute a custom query, which I create dynamically with a StringBuilder because of it's complexity.
How can I pass it to my class mapper.xml file ?
I've heard about #SelectProvider, but ? can't find complete examples... Can someone give me a step by step guide ?
I was also reading of The SQL Builder Class, of MyBatis, following the official guide but I miss how to launch that query/object I've created. By the way this doesn't seems the right way to me, because of the complexity of the query I have to build. Following the guide it seems I can't use contidional operators like IF or FOR to create the query string... So it can't work for my use.
thanks.

I only use #SelectProvider for java annotation ,this is a easy way to use it ,
this is my simple example earlier this year
1. create your provider class
package com.mybatis;
import java.util.Map;
import java.util.logging.Logger;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;
public class SqlProvider {
public String sqlProvider(Map<String, Object> map){
Logger.getLogger(SqlProvider.class.getName()).info("select * from student where id="+map.get("0"));
return "select * from student where id="+map.get("0");
}
public String findById(#Param("id") int id){
return new SQL(){{
SELECT("id,name,info");
FROM("student");
WHERE("id="+id);
}
}.toString();
}
}
you can use a string produce your sql query ,but also new SQL(){{some clauses such as SELECT(string),WHERE(string) etc.
}}.toString();
2. use your provider class in Mapper interface
we can use #SelectProvider(type=Class,method="methodName")
specified class and method
package com.mybatis;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
/*
*
*Stu is an entity map to your table in db
*
*/
#Mapper
public interface StuMapper {
#SelectProvider(type=SqlProvider.class,method="sqlProvider")
public Stus sqlProvider(Map<String, Object> map);
#SelectProvider(type=SqlProvider.class,method="findById")
public Stus findById_(#Param("id") int id);
}
Last , using you mapper .
more details ,see https://github.com/v5developer/maven-framework-project/blob/master/reference/Java.Persistence.with.MyBatis.3.pdf
especially in chapter 4.

<select id="methodName" resultMap="alarmPieEntry">
${your_raw_sql}
</select>
Just use ${your_raw_sql} variables in myClass_mapper.xml file , don't use #{your_raw_sql} .

Related

How to access AEM Core models in a Sling model

Specifically, I am trying to enable .SVG files to be usable by the core image component.
Right now I am making a sling model that ideally I would like to access the returned values of the getSrc() and getFileReference() classes in the core AEM Component interface located here.
I am very new to AEM development and Sling models. Am I missing some vital functionality that would let me do this?
Here is my code, which probably isn't at all helpful at this point.
package com.site.core.models;
import com.adobe.cq.wcm.core.components.models.Image;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.*;
import org.apache.sling.models.annotations.injectorspecific.*;
import org.apache.sling.settings.SlingSettingsService;
import javax.jcr.Node;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
#Model(adaptables = SlingHttpServletRequest.class)
public class ImageModel {
private String src = Image.getSrc();
return src;
}
As I mentioned in my comment, the link you are referring to is an interface, the implementation of that interface is here
In order to use your own implementation, you have two options:
In the image component html, change the data-sly-use to refer to your impl: com.site.core.models.ImageModel
Create a separate model that implements the Image interface and give it a high ranking to be picked up instead of the existing impl.
Disclaimer: I have not tested #2 but the documentation suggests that it's possible.

Can't resolve symbol toJson

I'm using json4s in a play project, and I'm also using a library called sbt-buildinfo which generates Scala source from your build definitions.
Now, in the sbt-buildinfo library the say you need to add some line of code: buildInfoOptions += BuildInfoOption.ToJson so you can use .toJson, but from some reason I can use .toJson.
this is how I do it:
import _root_.util.{AuthenticatedAction}
import buildinfo.BuildInfo
import com.google.inject.Inject
import org.json4s.BuildInfo
import play.api._
import play.api.mvc._
class AppInfo #Inject()(implicit configuration: Configuration) extends Controller {
def appVerion = AuthenticatedAction {
Ok(BuildInfo.toJson)
}
but the import buildinfo.BuildInfo stays gray....so it looks like I'm not using it. I refreshed the build.sbt and all, what could it be?
You have multiple imports to a BuildInfo object. org.json4s.BuildInfo will probably shadow your buildInfo.BuildInfo import and therefore, it does not have the required member. Try writing out the entire package name that you need:
Ok(buildinfo.BuildInfo.toJson)

How to define a NotesXspDocument Object in JAVA

In a JAVA bean that I am working on I want to pass a NotesXspDocument (could use a NotesDocument) to a method which looks like this:
public List<String> getReaders(NotesXspDocument thisXspDoc){
// do some stuff
}
But JAVA does not recognize the NotesXspDocument definition. I have imported the following packages:
import lotus.domino.NotesException;
import lotus.domino.Session;
import lotus.domino.Database;
import lotus.domino.View;
import lotus.domino.Document;
Is there a further package to import to make use the NotesXspDocument?
To elaborate on Jesses answer: in your case you need to do this to work with the XPages version of Document:
import com.ibm.xsp.model.domino.wrapped.DominoDocument;
public List<String> getReaders(DominoDocument thisXspDoc){
// do some stuff
}
NotesXspDocument is an SSJS-only alias; the real class is com.ibm.xsp.model.domino.wrapped.DominoDocument: http://public.dhe.ibm.com/software/dw/lotus/Domino-Designer/JavaDocs/DesignerAPIs/com/ibm/xsp/model/domino/wrapped/DominoDocument.html

Create a Table/Query with JPA/Hibernate in Play Framework

So I have Play Framework running at the moment with JPA and Hibernate. I'm completely new to both and the tutorials I've found around the web are above my head.
How in the world can I send a simple query or create a table? This is example code I've written up and I get: "RuntimeException: No EntityManager bound to this thread. Try wrapping this call in JPA.withTransaction, or ensure that the HTTP context is setup on this thread."
package controllers;
import play.Logger;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import play.db.jpa.JPA;
import play.mvc.Controller;
import play.db.*;
public class Database {
public static void initbuild() {
Logger.info("Checking database structure. The database will be restructured if not in the correct format.");
JPA.em().createQuery("create table test");
}
}
Le'ts start saying that you don't want to build the tables by yourself, just write your models under the models package annotating them by #Entity and the JPA plugin will automagically generate the tables matching the models that you have defined.
As for the error the error is raised cause you should annotate the method with the #Transactional annotation.
As stated in the official doc http://www.playframework.com/documentation/2.3.x/JavaJPA
"Every JPA call must be done in a transaction so, to enable JPA for a particular action, annotate it with #play.db.jpa.Transactional. This will compose your action method with a JPA Action that manages the transaction for you"
Hope it helped btw reading the doc and have a look to the computer-jpa example is suggested

Jena, DBpedia: RDF and model name

I'm using dbpedia in my app, and I'm using Jena for the semantic logic.
In Jena, the classes are:
Model: a set of statements
http://jena.sourceforge.net/javadoc/com/hp/hpl/jena/rdf/model/Model.html
Resource: http://jena.sourceforge.net/javadoc/com/hp/hpl/jena/rdf/model/Resource.html
In dbpedia, the rdf code of a resource is this:
e.g. http://dbpedia.org/resource/Frederick_of_Sweden
becomes http://dbpedia.org/data/Frederick_of_Sweden.rdf
If I call:
Model model = maker.createModel( "http://dbpedia.org/data/Frederick_of_Sweden.rdf")
A model with the name 'http://dbpedia.org/data/Frederick_of_Sweden.rdf' is created.
But I actually need to call it 'http://dbpedia.org/resource/Frederick_of_Sweden', to be consistent with the rdf statements. How do I name a model?
If I want to navigate the graph and reach other nodes, which is the best way to store these statements? Do I need a separate model for each dbpedia resource, or can I merge all the statements in one big model?
Thanks for any hint!
Mulone
I don't think the way you create your models really affect the way you download the data. You can create your model with the URI identifier that you like.
Here I show an example that can give some ideas of how to separate the way you get your triples from DBPedia and the way you store them in your backend system.
From your question I assume you are using a database backend so my code is targeted to that kind of backend in Jena.
import java.sql.SQLException;
import com.hp.hpl.jena.util.FileManager;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.SimpleSelector;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.db.DBConnection;
import com.hp.hpl.jena.rdf.model.ModelMaker;
import com.hp.hpl.jena.rdf.model.ModelFactory;
public class TestJena {
public static void main(String[] args) throws java.lang.ClassNotFoundException, java.sql.SQLException {
Class.forName("com.mysql.jdbc.Driver");
//The database backend initialization.
DBConnection connection = new DBConnection(MY_DB, USER, PASS, "mysql");
ModelMaker dbMaker = ModelFactory.createModelRDBMaker(connection);
//A file manager to get the triples from the DBPedia revolvable URI.
FileManager fManager = FileManager.get();
fManager.addLocatorURL();
Model linkedDataModel =
fManager.loadModel("http://dbpedia.org/data/Frederick_of_Sweden.rdf");
//Now we copy the in-memory model into our DB backend.
//When the model is created you can give it the name that you like.
Model dbModel =
dbMaker.createModel("http://dbpedia.org/resource/Frederick_of_Sweden");
dbModel.add(linkedDataModel);
StmtIterator iter = dbModel.listStatements();
while (iter.hasNext()) {
Statement stmt = iter.nextStatement();
System.out.println(stmt);
}
linkedDataModel.close();
dbModel.close();
connection.close();
}
This example prints ...
[http://dbpedia.org/resource/Frederick_i_of_sweden, http://dbpedia.org/ontology/wikiPageRedirects, http://dbpedia.org/resource/Frederick_of_Sweden]
[http://dbpedia.org/resource/Frederick_I_%28of_Sweden%29, http://dbpedia.org/ontology/wikiPageRedirects, http://dbpedia.org/resource/Frederick_of_Sweden]
[http://dbpedia.org/resource/Frederick_I,_Landgrave_of_Hesse-Kassel, http://dbpedia.org/ontology/wikiPageRedirects, http://dbpedia.org/resource/Frederick_of_Sweden]
[http://dbpedia.org:8890/data/Frederick_of_Sweden.rdf, http://xmlns.com/foaf/0.1/primaryTopic, http://dbpedia.org/resource/Frederick_of_Sweden]
(....)

Categories

Resources