MyBatis to XML or CSV - java

Background
We have a list of tables in a database, we want to read them through select statements, then turn the result into csv files
Problem
I could use mybatis to load data from tableA then map it to a resultMap A, then using openCSV to save it as a csv file.
but I am seeking a generic way, which I only need to specify
<sql> select * from tableA </sql>
<csvFile> A.csv </csvFile>
<mapping> Table.1stName = CSV.firstName </Mapping>
<mapping> Table.2ndName = CSV.secondName </Mapping>
........
in my config.xml, and my program should be able to run the sql select
then map the resultset to a generic resutMap in mybatis? or turn
the results into xml or csv or any string format?
then I can composing the csv file using the mapping in my config
the key question is how to let the mybatis return a more generic format
of the resultset, rather than map it to a specific object.

#FlorianSchaetz indeed for low level parsing Spring JDBC comes in handy. Mybatis is a ORM, I didn't need to map the object. no need to using Mybatis. Finally the implementation is simple, Paring the XML using JAXB, then excute the sql using Spring JDBC, which returns a resultset, then according to the mapping names. extract data from the dataset, them amp to the right csv file field.

Related

How to use Hibernate 5.2.10 MySQL JSON support without AttributeConverter or customUserType to map to Java Entity Class?

I am trying to map the MySQL JSON column to Java Entity class. Looking for the cleanest way of doing this.
Upon doing some research found 3 possible ways:
Extending AbstractSingleColumnStandardBasicType
Create a custom UserType
Use an attribute Converter
I used an attribute converter to convert the JSON column from String (as MySQL driver makes it to a String) to my required type - this works with both the Hibernate V4.3.10 and V5.2.10
I tried to find if JSON is natively supported in Hibernate and found the PR https://github.com/hibernate/hibernate-orm/pull/1395, based on the PR looks like it does add JSON mapping to the MySQL Dialect hence letting Hibernate know about the JSON Column.
Does this mean I can use something like this to map to JSON Column in DB ?#Column(name="json_type_column")
Private Object correspondingJsonAttribute;
If I cannot use it like this and need to use one of the above 3 methods, is there a reason I would need to upgrade to get the registerColumnType( Types.JAVA_OBJECT, "json" ); which is part of the PR and is present in Hibernate V5.2.10, Do I get any more features from V5.2.10 that support JSON columns?
I also looked into the corresponding test case to understand how the JSON column mapping is being done https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/test/java/org/hibernate/test/bytecode/enhancement/access/MixedAccessTestTask.java, this uses #Access annotation via property, looks like it sets the corresponding JSON column variable in Entity to Map after converting it from String.
Any help is much appreciated.
Thanks!
Upon doing some research found 3 possible ways:
Extending AbstractSingleColumnStandardBasicType
Create a custom UserType
Use an attribute Converter
AttributeConvertor won't help you for this, but you can still use a custom UserType, or Hibernate Type Descriptors.
Does this mean I can use something like this to map to JSON Column in
DB?
#Column(name="json_type_column") Private Object
correspondingJsonAttribute;
No. The json type is just for JDBC so that Hibernate knows how to handle that JDBC object when setting a parameter on a PreparedStatement or when fetching a ResultSet.
Do I get any more features from V5.2.10 that support JSON columns?
No, but you just need to supply your own JSON type.
You can just use the hibernate-types which is available on Maven Central.
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
And use the provided JdonType from Hibernate Types as it works on MySQL, PostgreSQL, Oracle, SQL Server or H2 without doing any modifications.

Mapping an oracle number type in Hibernate

I have a column (OCPR_TIMESTAMP) in oracle of type NUMBER(18) and want to select this column using hibernate.
I have the hibernate mapping file mapped as..
<property name="timestamp" column="OCPR_TIMESTAMP" type="java.lang.Double" />
and the timestamp property in my VO as a Double type.
When I select a record, the timestamp is always returned as null.
An example of the data stored in this column is:
7.18575602814979E15
I have tried various different types in the hibernate mapping, any ideas?
Thanks
Apologies - the persistence method being used was not hibernate, this was a web service using jdbc template so column needed adding to query string. Thanks for your response anyway Tim.

how to get query result as XML in hibernate?

I am using struts2 with hibernate. Does anyone know if it is possible to return query result as XML instead of ArrayList of domain objects?
Hibernate by default maps and persists a database record thought POJO , but in fact it also supports persisting , mapping and representing a database record in XML by using an experimental features called Dynamic models.
For example , to output a record in XML:
/**Get the a new session that is in the DOM4J EntityMode**/
Session dom4jSession = session.getSession(EntityMode.DOM4J);
Element outputXML=(Element) dom4jSession.get(Employee.class, employeeId);
XMLWriter writer = new XMLWriter( System.out, OutputFormat.createPrettyPrint() );
writer.write( outputXML);
To configure the format of the outputted XML , you can only do it by mapping the entity in XML . AFAIK ,there are no annotation equivalent .
Hibernate is an Object-Relational Mapper, meaning it maps a Relational database to objects. You want to use Hibernate to return an object and then use an XML Serializer to convert to XML.
The Simple Serializer is probably the best one to get started with. The Website contains a lot of tutorials and examples.
http://simple.sourceforge.net/
However there are a ton of XML Serializers for Java:
http://karussell.wordpress.com/2009/09/03/xml-serializers-for-java/
Maybe you could, once you have the result use XStream to parse the entire result to XML. A simple tutorial on XStream is available here.

how to call stored procedure with multiple tables in hibernate hbm file and pojo and also java class

SELECT emp.employeeId, emp.employeeFirstName, comp.companyname, dept.departmentname
FROM Employeetable emp, Companytable comp, departmenttable dept
WHERE emp.employeeCompanyId=comp.companyId AND emp.EmployeeDepartmentID=dept.DepartmentID;
The employeetable hbm file:
<sql-query name="callrealtimeprocedure">
<return alias="employeetable" class="com.AdiSys.eRMS.entity.Employeetable"/>
<return-join alias="companytable" property="com.AdiSys.eRMS.entity.Employeetable"/>
<return-join alias="companytable" property="com.AdiSys.eRMS.entity.Employeetable"/>
</sql-query>
The employeetable pojo:
#NamedNativeQueries({
#NamedNativeQuery(
name = "callrealtimeprocedure",
query = "CALL realtime(:employeeId,:employeeFirstName)",
resultClass = Employeetable.class
)
})
#Entity
Similarly department hbm and pojo.
My java class after creating session:
Query EmplyeeQuery = session.createSQLQuery("CALL realtime(:employeeId,:employeeFirstName,:companyname,:departmentname)")
.addEntity(Employeetable.class)
.addEntity(Companytable.class)
.addEntity(Departmenttable.class)
.setParameter("employeeId", "")
.setParameter("employeeFirstName","")
.setParameter("companyname", "")
.setParameter("departmentname", "");
I'm not able to find out how to link up stored procedure sql query in hbm and pojo and java class
Well, for a start, I wouldn't have bothered with the stored procedure. The whole point of using Hibernate is that you don't need to write any SQL. If you're going to write SQL, then there's not much to be gained by using Hibernate.
A really good source of Hibernate documentation is http://www.hibernate.org/docs - if you go to the "Core Reference Manual" for whichever version of Hibernate you have, you'll find some really good examples on how to set up your POJOs.
Also, I don't know if you're planning to use Hibernate annotations. I like these - they're a lot less messy than using separate XML files. Have a look at the "Hibernate Annotations Reference Guide" (from the same link, under v3.5) for guidance on using them.

Use SQL Information to Populate Schema Documentation and Code Comments Using Hibernate Tools?

I have set up Hibernate Tools from within Eclipse to autogenerate classes based on an existing DB. For each of the tables I have documented them and each of their columns within SQL Server. Is there a way to use that documentation information to comment the generated classes and to populate the schema entity documentation? I see that there are meta tags that can be put in the hbm.xml mapping files, but since I have those autogenerated each time I'd need to either add them back in or continually merge in new changes, plus I'd ideally like to have the DB be the "truth" information and not store this sort of information in the mapping files. Does anyone know if this is possible and if so how to do it? Thanks...
Is there a way to use that documentation information to comment the generated classes and to populate the schema entity documentation?
To my knowledge, tables and columns comments are used in some of the the generated files, at least in the following templates from hibernate-tools.jar:
doc/tables/table.ftl
hbm/column.hbm.ftl
hbm/persistentclass.hbm.ftl
For example, in hbm/column.hbm.ftl:
<#if column.isFormula()>
<formula>${column.getFormula()}</formula>
<#else>
<column name="${column.quotedName}" ${c2h.columnAttributes(column)}<#if column.comment?exists && column.comment?trim?length!=0>>
<comment>${column.comment}</comment>
</column><#else>/>
</#if>
</#if>
But they aren't used in the templates for annotated POJOs, you'd have to modify the templates for this.
If you use Hibernate tool task to generate pojo classes out of HBM files and Database,It will add documentation in the generated java classes by default.You can see it in pojoTypeDeclaration ftl file.
/**
${pojo.getClassJavaDoc(pojo.getDeclarationName() + " generated by hbm2java", 0)}
*/
<#include "Ejb3TypeDeclaration.ftl"/>
${pojo.getClassModifiers()} ${pojo.getDeclarationType()} ${pojo.getDeclarationName()} ${pojo.getExtendsDeclaration()} ${pojo.getImplementsDeclaration()}
Where pojo.getClassJavaDoc will generate documentation if your hbm file has meta attribute declared such as CLASS_DESCRIPTION.

Categories

Resources