How do I insert a java List<String> using Mybatis? - java

I would like to insert a list of strings into a single column in my database using Mybatis. I've tried using a Custom TypeHandler but I can't even get Mybatis to invoke it.
For a more detailed report on what I've already done click here

While specifying parameters for INSERT statement do like this:
INSERT INTO tableName(a) VALUES(#{aVal, typeHandler=com.test.YourTypeHandler})
where aVal is the parameter that you have passed to statement. Also intead of full name of typehandler you can use it alias. But don't forget to register it(typeHandler) in configuration file of MyBatis
edited
A good practise is specifying a type of value to be inserted like this:
#{aVal, jdbcType=VARCHAR, typeHandler=com.test.YourTypeHandler}. It will save you from issues with null values of aVal

Related

Access user defined method properties on query - Esper

I implemented a query where i mined data from a database but i have to change it so i mine my data from a custom function in my code. I read the documentation and added the annotation import on the configuration. The query throws that error:
Failed to resolve event type, named window or table by name 'path.to.my.class.customfunction'
I don't know the type that my function have to return but i tried Arraylist and Hashmaps with key an integer and value a custom class and didn't work.
My final query want to look like this :
select * from LocationEvent as loc,
***CustomFuntion()*** as product
where loc.id=product.id ;
I kept the structure i used for database connection. I don't know if there is another way to solve this. Thanks.
EDIT: I managed to make call the custom function with that query :
select path.to.class.getProducts() as product from pattern[every timer:interval(3 sec)]
My function right now return an ArrayList and the query returns this:
[Product{ProductID=124,.....,},Product{...}]
So now my problem is that i can't access properties of Product on the query like products.ProductID
If you want to have a custom function in the from-clause you can use the "method:". The docs have this described here: Accessing Non-Relational Data via Method. The Esper runtime then calls your method to get events/rows.

Mybatis insert fail when add more parameter

I'm using Mybatis 3.2, Orace 12c for my project. I used code generator to generate insert() method. In the <insert> tag it has schema name; for ex:
insert into CPORTAL.CARD_USER_MASTER
Now, the schema is dynamic, so I put the parameter to change the schema:
insert into ${schema}.CARD_USER_MASTER
Parameter schema is defined in mapper.java as
insert(CardUserMaster record, #Param("schema") String schema)
However, without that schema, insert works but when has schema, error happen:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'carduserSeqno' not found. Available parameters are [0, schema, param1, param2]
In other class I set schema parameter like that on insert method and it works. Don't know what happen to this class.
Any comments will be appreciated.
Thanks.
Change it to
insert(#Param("entity") CardUserMaster record, #Param("schema") String schema)
and use the params as entity.carduserSeqno in the SQL.
Looks like it cannot recognize that 0 parameter is POJO. Without the #Param("schema") it uses pojo fields directly as params btu with adding the schema param it cannot.

Hibernate. How to create an empty table from ResultSetMetaData?

I have a ResultSetMetaDataobject.
PreparedStatement ps=con.prepareStatement("select var1, var2 from test1, test2");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
I need to create an new empty table with all the fields in the above ResultSetMetaData
Open a new connection in different database
Use the meta data above
Create a new empty table with this meta data
I can see two possible solutions
Reflection. In general to create a table with Hibernate, I need to create a bean. But I don't know in advance what fields the ResultSetMetaData will contain . Should I create this bean with reflection?
HQL CREATE TABLE . Is this possible?
What is the simplest way to do this? How can I do this?
Couple of solutions that I can think of:
SchemaExport - Iterate through your ResultSetMetaData which exposes API's like getColumnName and getColumnType to get the information you need. Using this information create a hibernate mapping XML and send it to SchemaExport.create.
// yourClassMapper.xml generated in runtime
Configuration config = new Configuration();
config.addResource("yourClassMapper.xml");
new SchemaExport(config).create(true,true)
Native Query - As Usual Iterate through your metadata to figure out what should the columns be.
Using createSQLQuery or even using createNativeQuery
session.createSQLQuery("create table .....").executeUpdate();
This link provides an explanation on how to create custom fields. You can make use of its DOM Parser for 1st approach or create just tables and use the method mentioned in this blog to create custom fields. (Refer to this class MappingManager and its related custom map configuration)
Lastly, You need 2 different datasource to be configured for this. And inject the second database's source for creating session/sessionfactory in above implementations.
I dont think you need to create bean for it. If you want to create new table with same fields then simple fire this query on database using hibernate or jdbc.
SHOW CREATE TABLE tablename
Now simply change the name of the table in query, can be easily done in Java.
Now you does not need to create any bean for newly created table.
There are two ways for fetching data from table in hibernate. First way is get table data in form of bean object, another way is fire sql query and get data in form of Object (Java Class). you can get data in form of Object and Object Array using hibernate.
When we use join query in hibernate, then there is no specific type of bean is available for handling result of join because it contain column from multiple table so you will get data in form of Object and Object Array.
Just get Data in form of Object or Object Array.
Check This Link of my github... not exactly what you want but still will help :
here
I hope I Helped you.

How to use 'Insert' in a nativeSQL query in Hibernate outside the mapped class ?

In Hibernate, you can use the 'SELECT' queries in native SQL like this :
Query query = session.createSQLQuery("SELECT ... FROM ...");
But I would want to use an 'INSERT' query.
So, I looked at the documentation, and it seems you must go directly to the mapped class and write the code inside it.
But I would want to use it as I do for a 'SELECT' query (outside the mapped class) since it looks much more pratical.
Indeed, why would the treatment be different between 'SELECT' and 'INSERT' for a hibernate native SQL query ?
An HQL INSERT cannot be used to directly insert arbitrary entities—it can only be used to insert entities constructed from information obtained from SELECT queries (unlike ordinary SQL, in which an INSERT command can be used to insert arbitrary data into a table, as well as insert values selected from other tables).
Here’s the syntax of the INSERT statement:
INSERT INTO path ( property [, ...]) select
The name of an entity is path. The property names are the names of properties of entities listed in the FROM path of the incorporated SELECT query. The select query is an HQL SELECT query (as described in the next section).
As this HQL statement can only use data provided by an HQL select, its application can be limited. An example of copying users to a purged table before actually purging them might look like this:
Query query=session.createQuery("insert into purged_accounts(id, code, status) "+
"select id, code, status from acount where status=:status");
query.setString("status", "purged");
int rowsCopied=query.executeUpdate();
Or you can use
session.persist(obj);
where obj is the object of the POJO class let say TestClass
TestClass obj=new TestClass('','',''); //paramatrized constructor for the values you want to insert in your database.

How to call Oracle function returning Table of record

I have to get data from a function which returns a table of record. For example
Package is pkg1
Record defined inside package is:
type rec is record(id number,name varchar2(40));
Table of Record defined inside package is:
type rec_tbl is table of rec;
Function defined inside package is :
FUNCTION get_rec_tbl() RETURN rec_tbl;
Now What I need to do is: Using spring jdbc or spring jdbctemplate get values from function and process it. I am not sure how to do this.
Can some one help?
RECORD type is not directly supported by Oracle JDBC drivers.
There is an ugly workaround, as an official JDBC reference states. Never used it myselft, thought.
As a workaround you can just run such select query:
select * from table(get_rec_tbl())

Categories