Wednesday, 15 December 2010

SmartFoxServer 2x and Hibernate

I've been looking at using Object/Relational Mapping (ORM) to link my database and server extension in SmartFoxServer since reading the SmartFoxServer white paper on developing an MMO. Hibernate is one I've heard of, so I've been starting with that.

An ORM tool basically abstracts out connecting your objects to the database. It's possible to do all of this in SmartFoxServer using the in-built database manager, but not without some fairly intricate and repetitive code-wrangling. Hibernate should (in theory) take out a lot of the CRUD work.

To configure the connection between Hibernate and the database, you create a hibernate.cfg.xml file. This goes in the root of the src folder for the project, and includes all the settings for the connection, including which driver, which database etc. This clearly supersedes the information set up in the SFS2X database manager, so we could probably not bother setting that up.

Each object in the model that gets saved out to the database needs an xml file mapping the tables and columns in the database to the types and objects in the class. I'm putting these xml files in the same packages as the classes themselves. The hibernate.cfg.xml requires the full mapping to these files, including the package path. (e.g. <mapping resource="uk/ac/sussex/model/User.hbm.xml" /> not just <mapping resource="User.hbm.xml" />)

All of the xml files get included when I package up the .jar file for the extension.

To get the system up and running I needed to include the following jars:

These all needed to be included in the same folder as my extension (so {wherever}/SFS2X/extensions/gameBackend) NOT in the __lib__ folder of my extension (so {wherever}/SFS2X/extensions/__lib__) . When I put them in there hibernate then couldn't find the hibernate.cfg.xml unless I put that file separately into the root of my SFS2X installation, rather than leaving it in the extension jar. That would mean that I couldn't use separate hibernate configurations for each extension, which would be a bit ridiculous.

The server needed restarting once all of the jars had been put in place. I still haven't got the log4j stuff up and running correctly - I think SFS2X already uses log4j, so there's probably something in the configuration somewhere that needs changing, but I've not really looked into it yet.

Setting the project up like this also means that I can write JUnit tests for my model objects, provided that I include all of the same jars in the build path. The database connection does not depend on having SmartFoxServer running, so the objects are more server-independent (although now reliant on Hibernate! Swings and roundabouts I guess.)

No comments:

Post a Comment