MyBatis generator doesn't want to generate the code for me.
I use an Eclipse IDE for that.
At first I suspect targetProject property, but I specify the current folder for that and actually there is no result as well.
I work OK with the same xml conf from the command-line.
I think that I have to provide into my Java code the outputFolder some how, I tried prop.setProperty("generated.source.dir", System.getProperty("user.dir")); but it doesn't work.
So, any suggestions will be appreciated.
Here is my java code for generation
public class GeneratorMyBatis {
public static void main(String args[]) {
try {
generate();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void generate() throws Exception {
System.out.println("Working Directory = " + System.getProperty("user.dir"));
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("src//main//resources//mybatis//generator//config//generatorConfig.xml");
Properties prop = new Properties();
prop.setProperty("generated.source.dir", System.getProperty("user.dir"));
ConfigurationParser cp = new ConfigurationParser(prop, warnings);
Configuration config = cp.parseConfiguration(configFile);
config.validate();
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
ProgressCallback progress = new VerboseProgressCallback();
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(progress);
}
}
My configuration xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--
<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />
-->
<context id="MyTables" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/my_db"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="model" targetProject="\">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="xml" targetProject="\">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="dao" targetProject="\">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table schema="my_db" tableName="assignment" domainObjectName="Assignment" >
<property name="useActualColumnNames" value="true"/>
<generatedKey column="id" sqlStatement="MySql" identity="true" />
</table>
</context>
</generatorConfiguration>
I got this log messages
Introspecting table my_db.assignment
Generating Example class for table assignment
Generating Record class for table assignment
Generating Mapper Interface for table assignment
Generating SQL Map for table assignment
Saving file AssignmentMapper.xml
Saving file AssignmentExample.java
Saving file Assignment.java
Saving file AssignmentMapper.java
All in all I found out the how to fix the issue.
MyBatis generates the all necessary staff, but puts it into the disk root, like D:\ for example.
To configure on java targetProject and targetPackage, you have to set them into the Configuration object. Something like this:
Configuration config = cp.parseConfiguration(configFile);
config.getContexts().get(0).getJavaModelGeneratorConfiguration().setTargetProject(TARGET_PROJECT_PATH);
config.getContexts().get(0).getJavaModelGeneratorConfiguration().setTargetPackage(MODEL_TARGET_PACKAGE);
config.getContexts().get(0).getSqlMapGeneratorConfiguration().setTargetProject(TARGET_PROJECT_PATH);
config.getContexts().get(0).getSqlMapGeneratorConfiguration().setTargetPackage(XML_MAPPER_TARGET_PACKAGE);
Related
Maybe it is a simple question, but I can't find out this situation of relations in Hibernate.
I have these Entities:
#Entity
public class User {
...
#OneToMany(mappedBy = "user")
private Set<Conversation> posts = new HashSet<Conversation>();
...
}
#Entity
public class Conversation {
...
#OneToMany(mappedBy = "conversation")
private Set<Message> messages = new HashSet<Message>();
...
}
#Entity
public class Message { ... }
and then I want create User with Conversation and Message at once. Idea should be like this:
User user = new User();
user.getPosts().add(new Conversation(){
{
getMessages().add(new Message());
}
});
session.persist(user);
But just User is saved in database - why isn't it all? Because of default LAZY fetching? Could my idea be implemented somehow?
PS: Of course I know about the solution of persisting each of the entities, but I am used to do like this in other frameworks like nette or Django, so I can't get out of my head.
PPS: I found out that problem is in default CascadeType. Could it be set on globally, e.g. in Hibernate config XML? Is it a good idea (by performance point of view - it is persisted each time on "superpersist" or only in case of changes)?
PPPS: I also found out (opposite to Django) that I have to set FK ex-post for each item added to collection. It is natural (because of selected pure Set type), but new for me. Which approach would you recommend me? Required FK as argument in constructor on item Entity e.g.:
Class Message{
Message(Conversation conversation){
setConversation(conversation);
}
...
}
or make a method for adding where FK sets inside e.g.:
Class Conversation{
...
public void addMessage(Message msg){
msg.setConversation(this);
getMessages().add(msg);
}
...
}
?
Making Session + configure XML.
private final static String CFG = "hibernate-cfg.xml";
private final static String SCRIPT_FILE = "query.sql";
private static SessionFactory sessionFactory;
private static ServiceRegistry buildRegistry() {
return new StandardServiceRegistryBuilder()
.configure(CFG)
.build();
}
private static Metadata getMetaData() {
return new MetadataSources(buildRegistry()).getMetadataBuilder().build();
}
private static SessionFactory buildSessionFactory() {
return getMetaData().getSessionFactoryBuilder().build();
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
public static Session getSession(){
try {
return getSessionFactory().openSession();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
and the hibernate-cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/learnme
</property>
<property name="connection.username">root</property>
<property name="connection.password"/>
<property name="connection.pool_size">100</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Display all generated SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="learnme.hibernate.entities.User"/>
<mapping class="learnme.hibernate.entities.Conversation"/>
<mapping class="learnme.hibernate.entities.Message"/>
</session-factory>
</hibernate-configuration>
According to this and this
you need to have this in your persistence.xml file to set it globally:
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<cascade-persist/>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
The mapping file has to be located either in the default location,
META-INF/orm.xml, or in another location that is specified explicitly
in the persistence unit definition (in persistence.xml).
I have Spring context in src/main/resources
<bean id="dataSource"
class="org.postgresql.ds.PGSimpleDataSource">
<property name="serverName" value="localhost"/>
<property name="databaseName" value="bookcompany"/>
<property name="user" value="thisadmin"/>
<property name="password" value="thisadmin"/>
</bean>
I want to update the "value" of each property value from Java swing GUI
screenshoot : Java Swing GUI for select database properties
This is my Java GUI code:
private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {
String serverNew = serverName.getText();
String databaseNew = databaseName.getText();
String dbUsernameNew = databaseName.getText();
String dbPasswordNew = databasePassword.getText();
//???
}
Is it possible to update property value of my spring-context using data from java GUI??
Please help..
You can change those values if you create the object with #Bean and use #ComponentScan, but I am not sure if you can change the database connection parameters dynamically.
One thing you can do is to create a needed bean or object yourself after you have the values from GUI by extending PersistenceUnitInfo if you want a database connection, for example.
I have found a solution, I use the Properties file to store property values. Then my Spring context file uses that properties file.
First, I update Spring context file to this :
<context:property-placeholder location="file:./jdbc.properties" />
<bean id="dataSource"
class="org.postgresql.ds.PGSimpleDataSource">
<property name="serverName" value="${db.server}"/>
<property name="databaseName" value="${db.database}"/>
<property name="user" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
I update my Java code :
String serverNew = serverName.getText();
String databaseNew = databaseName.getText();
String dbUsernameNew = databaseName.getText();
String dbPasswordNew = databasePassword.getText();
Properties props = new Properties();
File f = new File("./jdbc.properties");
if (f.exists()) {
props.load(new FileReader(f));
props.setProperty("db.host", serverNew);
props.setProperty("db.database", databaseNew);
props.setProperty("db.username", dbUsernameNew);
props.setProperty("db.password", dbPasswordNew);
f.createNewFile();
}
out = new FileOutputStream(f);
props.store(out, null);
I have created a simple Member Model Class and trying to retrieve all the members from the DB using Hibernate.
The hibernate.cfg.xml is as follows :
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://192.168.0.112:1433;DatabaseName=WBSEDCL</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">Asdf#123</property>
<property name="hibernate.connection.autocommit">true</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<!-- Mapping files -->
<mapping resource="Member.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The Code For List members is as follows :
#SuppressWarnings("deprecation")
public static ArrayList<Member> listMembers(){
Session sessionNew = null;
ArrayList<Member> membrArray = new ArrayList<Member>();
try{
/* This step will read hibernate.cfg.xml and prepare hibernate for use */
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactoryNew = configuration.buildSessionFactory(ssrb.build());
sessionNew = sessionFactoryNew.openSession();
String SQL_QUERY ="SELECT * FROM Member membr";
Query query = sessionNew.createQuery(SQL_QUERY);
for(Iterator it=query.iterate();it.hasNext();){
Object[] row = (Object[]) it.next();
Member membr_obj = new Member((String)row[0],(String)row[1],(String)row[2],(String)row[3],(String)row[4],(String)row[5],(String)row[6],(String)row[7],
(String)row[8],(String)row[9],(String)row[10],(String)row[11],(String)row[12],(String)row[13],(String)row[14],(String)row[15],(String)row[16],(String)row[17],
(String)row[18],(String)row[19],(String)row[20],(String)row[21],(String)row[22],(String)row[23],(String)row[24],(String)row[25],(String)row[26],
(String)row[27],(String)row[28],(String)row[29],(String)row[30],(String)row[31],(String)row[32],(String)row[33],(String)row[34],(String)row[35],
(String)row[36],(String)row[37],(String)row[38],(String)row[39],(String)row[40],(String)row[41],(String)row[42],(String)row[43],
(String)row[44],(String)row[45],(String)row[46],(String)row[47],(String)row[48],(String)row[49],(String)row[50],(String)row[51],(String)row[52],(String)row[53]);
membrArray.add(membr_obj);
}
}
catch(Exception exception){
System.out.println("Exception in listMember Function in PersistenceManager");
exception.printStackTrace();
}
finally{
/* Actual contact insertion will happen at this step*/
sessionNew.flush();
sessionNew.close();
}
return membrArray;
}
Whenever the code is executed and the method is invoked by a calling function then a nullpointerexception is thrown at
sessionNew.flush();
sessionNew.close();
Within The finally Block.
What am I doing wrong ?
sessionNew is not initialized as you expect it to be. There seems to be an exception thrown either before its initialized or at the point of initializing it. The code should have run the catch block sysout statement after the exception is thrown. Since Finally block always run, it just gets executed calling flush() on a null object. Please check why sessionNew is not getting initialized. Try to debug and check it.
I generated an UML file using modelio.
I applied stereotypes on my classes.
My .uml file :
<?xml version="1.0" encoding="UTF-8"?>
<xmi:XMI xmi:version="2.1" xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:LocalProfile="http:///schemas/LocalProfile/_TS6FwP2iEeKR1arwT6_zsA/0" xmlns:default="http:///schemas/default/_TTEd0P2iEeKR1arwT6_zsA/0" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" xmlns:uml="http://www.eclipse.org/uml2/3.0.0/UML" xsi:schemaLocation="http:///schemas/LocalProfile/_TS6FwP2iEeKR1arwT6_zsA/0 LocalProfile.profile.uml#_TUTM5v2iEeKR1arwT6_zsA http:///schemas/default/_TTEd0P2iEeKR1arwT6_zsA/0 default.profile.uml#_TUkSp_2iEeKR1arwT6_zsA">
<uml:Model xmi:id="_TSufkP2iEeKR1arwT6_zsA" name="xmitojava">
<eAnnotations xmi:id="_TSufkf2iEeKR1arwT6_zsA" source="Objing">
<contents xmi:type="uml:Property" xmi:id="_TSufkv2iEeKR1arwT6_zsA" name="exporterVersion">
<defaultValue xmi:type="uml:LiteralString" xmi:id="_TSufk_2iEeKR1arwT6_zsA" value="2.2"/>
</contents>
</eAnnotations>
<ownedComment xmi:id="_TSuflP2iEeKR1arwT6_zsA">
<body></body>
</ownedComment>
<packagedElement xmi:type="uml:Package" xmi:id="_TSuflf2iEeKR1arwT6_zsA" name="com.imcfr.pkg">
<packagedElement xmi:type="uml:Class" xmi:id="_TSuflv2iEeKR1arwT6_zsA" name="Group">
<ownedAttribute xmi:id="_TSufl_2iEeKR1arwT6_zsA" name="label" visibility="private" isUnique="false" isReadOnly="true">
<type xmi:type="uml:PrimitiveType" href="pathmap://UML_LIBRARIES/UMLPrimitiveTypes.library.uml#String"/>
</ownedAttribute>
</packagedElement>
<packagedElement xmi:type="uml:Association" xmi:id="_TSufmP2iEeKR1arwT6_zsA" memberEnd="_TSufmf2iEeKR1arwT6_zsA _TSufn_2iEeKR1arwT6_zsA">
<ownedEnd xmi:id="_TSufmf2iEeKR1arwT6_zsA" type="_TSufnP2iEeKR1arwT6_zsA" association="_TSufmP2iEeKR1arwT6_zsA">
<upperValue xmi:type="uml:LiteralUnlimitedNatural" xmi:id="_TSufmv2iEeKR1arwT6_zsA" value="*"/>
<lowerValue xmi:type="uml:LiteralInteger" xmi:id="_TSufm_2iEeKR1arwT6_zsA"/>
</ownedEnd>
</packagedElement>
<packagedElement xmi:type="uml:Class" xmi:id="_TSufnP2iEeKR1arwT6_zsA" name="User">
<ownedAttribute xmi:id="_TSufnf2iEeKR1arwT6_zsA" name="login" visibility="protected" isUnique="false" isReadOnly="true">
<type xmi:type="uml:PrimitiveType" href="pathmap://UML_LIBRARIES/UMLPrimitiveTypes.library.uml#String"/>
</ownedAttribute>
<ownedAttribute xmi:id="_TSufnv2iEeKR1arwT6_zsA" name="password" visibility="protected" isUnique="false" isReadOnly="true">
<type xmi:type="uml:PrimitiveType" href="pathmap://UML_LIBRARIES/UMLPrimitiveTypes.library.uml#String"/>
</ownedAttribute>
<ownedAttribute xmi:id="_TSufn_2iEeKR1arwT6_zsA" name="group" type="_TSuflv2iEeKR1arwT6_zsA" isReadOnly="true" aggregation="shared" association="_TSufmP2iEeKR1arwT6_zsA">
<lowerValue xmi:type="uml:LiteralInteger" xmi:id="_TSufoP2iEeKR1arwT6_zsA"/>
</ownedAttribute>
</packagedElement>
</packagedElement>
<profileApplication xmi:id="_TVRdQP2iEeKR1arwT6_zsA">
<eAnnotations xmi:id="_TVT5gP2iEeKR1arwT6_zsA" source="http://www.eclipse.org/uml2/2.0.0/UML">
<references xmi:type="ecore:EPackage" href="LocalProfile.profile.uml#_TUTM5v2iEeKR1arwT6_zsA"/>
</eAnnotations>
<appliedProfile href="LocalProfile.profile.uml#_TUSl0P2iEeKR1arwT6_zsA"/>
</profileApplication>
<profileApplication xmi:id="_TVUgkP2iEeKR1arwT6_zsA">
<eAnnotations xmi:id="_TVUgkf2iEeKR1arwT6_zsA" source="http://www.eclipse.org/uml2/2.0.0/UML">
<references xmi:type="ecore:EPackage" href="default.profile.uml#_TUkSp_2iEeKR1arwT6_zsA"/>
</eAnnotations>
<appliedProfile href="default.profile.uml#_TUkSoP2iEeKR1arwT6_zsA"/>
</profileApplication>
</uml:Model>
<LocalProfile:Stereo xmi:id="_TVWVwP2iEeKR1arwT6_zsA" base_Class="_TSuflv2iEeKR1arwT6_zsA"/>
<default:metaclass xmi:id="_TVW80P2iEeKR1arwT6_zsA" base_Classifier="_TSufnP2iEeKR1arwT6_zsA"/>
</xmi:XMI>
I have default.profile.uml and LocalProfil.profile.uml in the same folder than my .uml file.
I use this code to get my UML2 Model :
URI typesUri = URI.createFileURI(path);
ResourceSet set = new ResourceSetImpl();
set.getPackageRegistry().put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
set.getResourceFactoryRegistry().getExtensionToFactoryMap().put(UMLResource.FILE_EXTENSION, UMLResource.Factory.INSTANCE);
set.createResource(typesUri);
Map<URI, URI> uriMap = set.getURIConverter().getURIMap();
URI uri = URI.createURI("jar:file:/C:/Users/ffischer/Desktop/org.eclipse.uml2.uml.resources_3.1.1.v201008191505.jar!/");
uriMap.put(URI.createURI(UMLResource.LIBRARIES_PATHMAP), uri.appendSegment("libraries").appendSegment(""));
uriMap.put(URI.createURI(UMLResource.METAMODELS_PATHMAP), uri.appendSegment("metamodels").appendSegment(""));
uriMap.put(URI.createURI(UMLResource.PROFILES_PATHMAP), uri.appendSegment("profiles").appendSegment(""));
Resource r = set.getResource(typesUri, true);
Model m = (Model) EcoreUtil.getObjectByType(r.getContents(), UMLPackage.Literals.MODEL);
Everything works fine, except that I can't get stereotypes associed with my classes.
(for exemple, this code send me empty arrays :)
ClassImpl _c = (ClassImpl) el;
System.out.println(_c.getName() + " stereotypes :");
System.out.println(_c.getStereotypeApplications());
System.out.println(_c.getApplicableStereotypes());
System.out.println(_c.getAppliedStereotypes());
I think maybe I forget to do one step but I don't see which.
I hope someone can help me :)
I found the solution :
uriMap.put(URI.createURI("LocalProfile.profile.uml"), URI.createURI("src/main/resources/LocalProfile.profile.uml"));
uriMap.put(URI.createURI("default.profile.uml"), URI.createURI("src/main/resources/default.profile.uml"));
Indeed, there was the wrong path. Now, everything works fine, hope this post will help others :)
Hi i am developing a spring mvc app thats using hibernate to connect to a mysql database that stores files.
I have two methods. one that adds all files from a specific file path of my choosing and another method that invokes a query to return me a list of the files stored from mysql.
The issue is this. When i execute the first method on its own ie populating the database, it works fine i can see the contents of that table from mysql command line. however, when i then execute the query method right after populating it, the contents of that said table is completely gone instantly. Its as if hibernate only stored the data in the mysql temporarily or somewhere in mysql, it deleted data imediatly and doesnt keep it their.
this is the method that populated the table:
/**
* Test Method: ideal for another class to do this kind of work and this
* pass the FileObject into this class
*/
public void addSomeFiles() {
System.out.println("addSomeFiles");
File dir = new File(picturesPath);
String[] fileNames = dir.list();
for (int i = 0; i < fileNames.length; i++) {
System.out.println(fileNames[i]);
File file = new File(picturesPath + "\\" + fileNames[i]);
if (file.isFile()) {
FileObject fileO = contstructFileObject(file);
if (fileO == null) {
System.out.println("fileO is null!!!!!");
} else {
// addFile(fileO);
dbFileHelper.addFile(fileO);
}
}
}
System.out.println("//////////////");
// File file;
}
.........Hibernate template class........
public class DbFileHelper implements DbFileWrapper {
private HibernateTemplate hbTemplate;
//private static final String SQL_GET_FILE_LIST = "select filename, size, id, type from fileobject";
private static final String SQL_GET_FILE_LIST = "select new FileObject(filename, size, id, type) from FileObject";
public DbFileHelper() {
}
public void setHbTemplate(HibernateTemplate hbTemplate) {
System.out.println("setHbTemplate");
System.out.println("///////////////////");
System.out.println("///////////////////");
System.out.println("///////////////////");
this.hbTemplate = hbTemplate;
}
// ////////////////////////////////////////////////
#Override
public String addFile(FileObject file) {
// TODO Auto-generated method stub
System.out.println("addFile using hibernate");
if (hbTemplate == null) {
System.out.println("hbTemplate is null!! why?");
}
hbTemplate.saveOrUpdate(file);
hbTemplate.flush();
return "added succesfuly";
}
And here is the other method that makes the query:
........................
public JSONArray getFileList(String type){
return constructJsonArray(dbFileHelper.getFileList(ALL));
}
private JSONArray constructJsonArray(List<FileObject> fileList ){
JSONArray mJsonArray = new JSONArray();
for (int i = 0; i < fileList.size(); i++) {
System.out.println("fileName = " + fileList.get(i).getFilename() );
//mJson.put("Filename", fileList.get(i).getFileName() );
mJsonArray.add( new JSONObject().put("File ID", fileList.get(i).getId() ));
mJsonArray.add( new JSONObject().put("Filename", fileList.get(i).getFilename() ));
mJsonArray.add( new JSONObject().put("File type", fileList.get(i).getType()));
mJsonArray.add( new JSONObject().put("File Size", fileList.get(i).getSize()));
}
return mJsonArray;
}
..........hibernate Template class.......
private static final String SQL_GET_FILE_LIST = "select new FileObject(filename, size, id, type) from FileObject";
#Override
public List<FileObject> getFileList(String type) {
// TODO Auto-generated method stub
List<FileObject> files = hbTemplate.find(SQL_GET_FILE_LIST);
//hbTemplate.flush();
return files;
}
..........
Finally here is a print screen of what i originaly put inside my table but dissapears on its own:
http://img411.imageshack.us/img411/9553/filelisti.jpg
Am i missing something here?
edit: additional info.
my hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.kc.models.FileObject" >
<class name="com.kc.models.FileObject" table="fileobject">
<id name="id" column="ID">
<generator class="native" />
</id>
<property name="filename" type="string" column="FILENAME" />
<property name="type" type="string" column="TYPE" />
<property name="size" type="double" column="SIZE" />
<property name="file" type="blob" length="1000000000" column="FILE" />
</class>
</hibernate-mapping>
my controller:
#Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO call a method that returns a list of Mobile Apps.
testAddingSomeFilesToDb();
return new ModelAndView("" + "testJsonResponse", "jsonArray",
getFileList() );
}
private void testAddingSomeFilesToDb() {
ctx = new ClassPathXmlApplicationContext("zang-file-service.xml");
FileHelper file = (FileHelper) ctx.getBean("fileHelper");
file.addSomeFiles();
}
/**
* Get file list from sql server based on type
* #return file list in json
*/
private JSONArray getFileList() {
// TODO: Get request parameter that states what type of file extensions
// the client wants to recieve
ctx = new ClassPathXmlApplicationContext("zang-file-service.xml");
FileHelper file = (FileHelper) ctx.getBean("fileHelper");
return file.getFileList("all");
}
Another edit:
my .xml file configuring the session factory and hibernate template
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<!-- http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd -->
<!-- Config properties files -->
<!-- Hibernate database stuff -->
<!-- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"> <list> <value>/properties/jdbc.properties</value>
</list> </property> </bean> -->
<!-- <bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" /> <property
name="url" value="${database.url}" /> <property name="username" value="${database.user}"
/> <property name="password" value="${database.password}" /> </bean> -->
<bean id="dataSource1"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/zangshop" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<!-- LocalSessionFactoryBean u need to put the hbm files in the WEB-INF/classes
root director -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource1"></property>
<property name="mappingResources">
<list>
<value>FileObject.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="hbTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="dbFileHelper" class="com.kc.models.DbFileHelper">
<property name="hbTemplate" ref="hbTemplate"></property>
</bean>
<bean id="fileHelper" class="com.kc.models.FileHelper">
<property name="dbFileHelper" ref="dbFileHelper"></property>
</bean>
</beans>
i have fixed the problem
i changed <prop key="hibernate.hbm2ddl.auto">create</prop>
to <prop key="hibernate.hbm2ddl.auto">update</prop> and it worked
Are you creating/destroying the SessionFactory between calls? Could you have the hbm2ddl.auto property set to create-drop?
Actually, can you show the Hibernate settings?
Reference
Hibernate Core Reference Guide
Table 3.7. Miscellaneous Properties
In my case also table was getting deleted automatically, following solution worked for me:
org.hibernate.dialect.MySQL8Dialect
Appending the version number with the MySQL Dialect.
Because commit was not getting executed earlier with org.hibernate.dialect.MySQLDialect.