Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, October 1, 2014

java.text.MessageFormat sucks

More on that in a minute.

In related news: Throwable.getLocalizedMessage() is practically useless, to the point it might as well be deprecated. I may be the only developer in the history of the Java language to actually implement that method.*

// java -Duser.language=fr
void printError(MyAwesomeException e) {
   System.out.println(e.getMessage()); // "by jove!"
   System.out.println(e.getLocalizedMessage()); // "sacrebleu!"
}

* Gross exaggeration

Now back to MessageFormat. By default it will only handle the formates built in to the JRE. Extending it is done per instance, by argument.

class ExceptionFormat extends Format {
    @Override
    public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
        if (!(obj instanceof Throwable)) throw new IllegalArgumentException();
        Throwable t = (Throwable) obj;
        String sMsg = t.getLocalizedMessage();
        if (sMsg == null) sMsg = t.getMessage();
        if (sMsg == null) sMsg = t.getClass().getName();
        toAppendTo.append(sMsg);
        return toAppendTo;
    }
    @Override
    public Object parseObject(String source, ParsePosition pos) {
        throw new UnsupportedOperationException();
    }
}

// java -Duser.language=fr
void printError(MyAwesomeException e) {
    MessageFormat mf = new MessageFormat("Error: {0}");
    mf.setFormatByArgumentIndex(0, new ExceptionFormat());
    System.out.println(mf.format(new Object[]{e})); // "Error: sacrebleu!"
}

Unfortunately, not only would be a hassle to manually set a custom format every time, it wouldn't even work half the time.

// java -Duser.language=fr
void logError(Exception e) {
   Logger log = Logger.getAnonymousLogger("fish");
   log.log(Level.WARN, "Error: {0}", new Object[] { e }); // "Error: by jove!"
   // NO!
}

MessageFormat is nested deep within the bowels of the JRE/JDK and many 3rd party libraries. It's permanently infected, so there's no way to override many cases.

While you can't get rid of MessageFormat entirely, there are a few better alternatives available.

ICU MessageFormat

If you are serious about localizing your app, it's just a matter of time before you start using the ICU library. It's pretty much an industry standard. The best part is it fixes the notorious apostrophe (') issue. You can also add arguments by name, as well as number. Unfortunately it doesn't solve my problem.

Apache lang ExtendedMessageFormat

Lets you register format factories, but only at the instance level.

class ExceptionFormatFactory implements FormatFactory {
    public Format getFormat(String name, String arguments, Locale locale) {
        if (!"exception".equals(name)) throw new IllegalArgumentException();
        return new ExceptionFormat();
    }
}

// java -Duser.language=fr
void printError(MyAwesomeException e) {
    Map<String, ExceptionFormatFactory> registry = new Map<String, ExceptionFormatFactory>();
    registry.put("exception", new ExceptionFormatFactory());
    ExtendedMessageFormat mf = new ExtendedMessageFormat("Error: {0,exception}");
    System.out.println(mf.format(new Object[]{e})); // "Error: sacrebleu!"
}

When using "choice" subformats, support for nested formatting instructions is limited to that provided by the base class.

Here is an example where there's no way around the notorious MessageFormat.

Humanize [Extended]MessageFormat

By jove this might be as good as it gets. This appears to actually let you register formatters at a global level so all uses of this class will automatically benefit.

public static class ExceptionFormatProvider implements FormatProvider {
    @Override
    public FormatFactory getFactory() {
        return new ExceptionFormatFactory();
    }
    @Override
    public String getFormatName() {
        return "exception";
    }
}

// java -Duser.language=fr
void printError(MyAwesomeException e) {
    System.out.println(Humanize.format("Error: {0,exception}", e)); // "Error: sacrebleu!"
}

Wednesday, January 27, 2010

Java and VNC on Windows

Sometime between JRE 1.6.0 update 3 and 1.6.0 update 15, something changed.

I use a VNC program heavily, and was surprised to see all Java Swing GUIs become almost useless because they would never refresh through VNC. Yet at the same time Netbeans still worked fine over VNC.

I sought high and low, but what kind of search string would you use for this issue?

As a work around at the time, I set the JAVA_HOME to an older JRE, and updated some of my Java program shortcuts to use "C:\Program Files\Java\jre1.6.0_3\bin\javaw.exe"

Today I finally found the issue and fix.

J2D_D3D=false

This problem might occur with any other kind of Remote Desktop program, or perhaps it is just those that use a special video driver.


Oh and Netbeans seems to run under the latest JDK installed instead of the latest JRE. Guess I should update that sometime.

Friday, May 1, 2009

Compounding Hibernate Problems

Platform information
Eclipse Platform
Version: 3.4.2
Build id: M20090211-1700

Hibernate Tools 3.2.4.GA-R200903141626-H5
and
Hibernate Tools 3.2.4.GA-N200904280907-H52

Windows XP Pro SP3

JRE 6

Tested on Oracle 10g and Apache Derby

Two problems with Hibernate Tools reverse engineering:

  1. Unable to create a relationship from a non-primary key column in one table to one column of a composite primary key in another table, and visa-versa.

  2. Creating a relationship from a column in a composite primary key of one table to a non-primary key column in another table produces incorrect mapping file (I have submitted a poorly written bug report for this one).

These issues will be explorered in the following example. For simplicity we’ll use an Apache Derby database.

Start the database, and connect to it.

jdbc:derby://localhost:1527/myDB;create=true;user=me;password=mine

Create these tables in the myDB database, in the ME schema.

ddl
create table vehicles (
    make_id integer,
    model_id integer,
    name varchar(50),
    PRIMARY KEY (make_id, model_id)
);

create table owners (
    owner_id integer PRIMARY KEY,
    favorite_make_id integer,
    name varchar(20)
);

insert into vehicles values (1, 0, 'Chevrolet Corvette');
insert into vehicles values (1, 1, 'Chevrolet Malibu');
insert into vehicles values (2, 0, 'Ford Focus');
insert into vehicles values (2, 1, 'Ford Mustang');
insert into vehicles values (3, 0, 'Honda Accord');
insert into vehicles values (3, 1, 'Honda Odyssey');
insert into vehicles values (4, 0, 'Toyota Avalon');
insert into vehicles values (4, 1, 'Toyota Camry');

insert into owners values (50, 3, 'Jim');
insert into owners values (51, 1, 'Alex');
insert into owners values (52, 4, 'Sue');
insert into owners values (53, 1, 'Casey');
insert into owners values (54, 3, 'Ted');
insert into owners values (55, 2, 'Mary');

Create this Hibernate Configuration file.

.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="hibernate.connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
        <property name="hibernate.connection.url">jdbc:derby://localhost:1527/myDB</property>
        <property name="hibernate.connection.username">me</property>
        <property name="hibernate.connection.password">mine</property>
        <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.default_schema">ME</property>
        <property name="hibernate.show_sql">true</property>
    </session-factory>
</hibernate-configuration>

Setup a Hibernate Console Configuration with the configuration above and connection to the Derby database.

Create this Hibernate reverse engineering configuration.

.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC
    "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
    <table-filter match-name="OWNERS"/>
    <table-filter match-name="VEHICLES"/>

    <table name="OWNERS">
        <foreign-key foreign-table="VEHICLES">
            <column-ref local-column="FAVORITE_MAKE_ID" foreign-column="MAKE_ID" />
        </foreign-key>
    </table>

</hibernate-reverse-engineering>

Setup a Hibernate Code Generation configuration like this:
[Main tab] [Exporters tab]

Trying to run it produces this error:

org.hibernate.MappingException: Foreign key (FK8BBD58205C954C50:OWNERS [FAVORITE_MAKE_ID])) must have same number of columns as the referenced primary key (VEHICLES [MAKE_ID,MODEL_ID])
Foreign key (FK8BBD58205C954C50:OWNERS [FAVORITE_MAKE_ID])) must have same number of columns as the referenced primary key (VEHICLES [MAKE_ID,MODEL_ID])

Searching for "must have same number of columns as the referenced primary key" on Google returns 6 pages of results. You can find references to this error as early as 2005.

The Other Way (incorrect)

So let’s try the other way, even though it’s incorrect.

Change the Hibernate reverse engineering configuration to this.

.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC
    "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
    <table-filter match-name="OWNERS"/>
    <table-filter match-name="VEHICLES"/>

    <table name="VEHICLES">
        <foreign-key foreign-table="OWNERS">
            <column-ref local-column="MAKE_ID" foreign-column="FAVORITE_MAKE_ID" />
        </foreign-key>
    </table>

</hibernate-reverse-engineering>

Now the Code Generation configuration will run, but it produces an incorrect mapping file.

Vehicles.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>
    <class name="Vehicles" table="VEHICLES">
        <composite-id name="id" class="VehiclesId">
            <key-property name="makeId" type="int">
                <column name="MAKE_ID" />
            </key-property>
            <key-property name="modelId" type="int">
                <column name="MODEL_ID" />
            </key-property>
        </composite-id>
        <many-to-one name="owners" class="Owners" update="false" insert="false" fetch="select">
            <column name="MAKE_ID" not-null="true" />
        </many-to-one>
        <property name="name" type="string">
            <column name="NAME" length="50" />
        </property>
    </class>
</hibernate-mapping>

The many-to-one tag should have this additional attribute:

property-ref="favoriteMakeId"

Because it doesn’t, this code will fail:

Main.java
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.*;

public class Main {

    public static void main(String[] args) {
        System.out.println("Connecting to Derby database.");
        SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory();
        Session session = sf.getCurrentSession();

        System.out.println("Querying for some vehciles.");
        session.beginTransaction();
        Query q = session.createQuery("from Vehicles as v where v.id.modelId = 0");
        java.util.List<Vehicles> vehicleList = q.list();

        System.out.println("Got " + vehicleList.size() + " matches.");

        for (Vehicles vehicle : vehicleList) {

            System.out.println("Getting an owner that likes the maker of " + vehicle.getName());
            Owners owner = vehicle.getOwners();
            try {
                System.out.println(owner.getName() + " likes it.");
            } catch (ObjectNotFoundException ex) {
                ex.printStackTrace();
                System.err.println("This fails because it was matching VEHCILES.MAKE_ID to OWNERS.OWNER_ID");
                System.err.println("when it SHOULD have matched to OWNERS.FAVORITE_MAKE_ID like the reveng says.");
            }
        }
    }

}

Program output:

Connecting to Derby database.
Querying for some vehciles.
Hibernate: select vehicles0_.MAKE_ID as MAKE1_0_, vehicles0_.MODEL_ID as MODEL2_0_, vehicles0_.NAME as NAME0_ from ME.VEHICLES vehicles0_ where vehicles0_.MODEL_ID=0
Got 4 matches.
Getting an owner that likes the maker of Chevrolet Corvette
Hibernate: select owners0_.OWNER_ID as OWNER1_1_0_, owners0_.FAVORITE_MAKE_ID as FAVORITE2_1_0_, owners0_.NAME as NAME1_0_ from ME.OWNERS owners0_ where owners0_.OWNER_ID=?
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [Owners#1]
    at org.hibernate.impl.SessionFactoryImpl$2.handleEntityNotFound(SessionFactoryImpl.java:409)
    at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:108)
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:97)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:140)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
    at Owners_$$_javassist_1.getName(Owners_$$_javassist_1.java)
    at Main.main(Main.java:23)
This fails because it was matching VEHCILES.MAKE_ID to OWNERS.OWNER_ID
...

However, even if you manually add the property-ref, when you run it with the example program, it returns an error of “More than one row with the given identifier was found”.

Connecting to Derby database.
Querying for some vehciles.
Hibernate: select vehicles0_.MAKE_ID as MAKE1_0_, vehicles0_.MODEL_ID as MODEL2_0_, vehicles0_.NAME as NAME0_ from ME.VEHICLES vehicles0_ where vehicles0_.MODEL_ID=0
Hibernate: select owners0_.OWNER_ID as OWNER1_1_0_, owners0_.FAVORITE_MAKE_ID as FAVORITE2_1_0_, owners0_.NAME as NAME1_0_ from ME.OWNERS owners0_ where owners0_.FAVORITE_MAKE_ID=?
Exception in thread "main" org.hibernate.HibernateException: More than one row with the given identifier was found: 1, for class: Owners
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:92)
    at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:108)
    at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:1672)
    at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:641)
    at org.hibernate.type.EntityType.resolve(EntityType.java:415)
    at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:139)
    at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:877)
    at org.hibernate.loader.Loader.doQuery(Loader.java:752)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
    at org.hibernate.loader.Loader.doList(Loader.java:2228)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2125)
    at org.hibernate.loader.Loader.list(Loader.java:2120)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401)
    at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:361)
    at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1148)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
    at Main.main(Main.java:14)

This is because the example column has non-unique entries. If it only had unique entires, our manual property-ref fix would work.

Doing it manually

Hibernate reverse engineering has pretty much no support for special table relationships (e.g. a non-inverse one-to-many). The only real solution to this problem is to manually create the mapping files and classes yourself.

Some links that probably won’t help at all:

Trying to use a composite-id with key-many-to-one won’t work because the foreign column needs to be a primary key.

Here is how the mapping of Vehicles → Owners should be:

Vehicles.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>
    <class name="Vehicles" table="VEHICLES">
        <composite-id mapped="false" >
            <key-property name="makeId" type="int" >
                <column name="MAKE_ID" />
            </key-property>
            <key-property name="modelId" type="int">
                <column name="MODEL_ID" />
            </key-property>
        </composite-id>
        <property name="name" type="string">
            <column name="NAME" length="50" />
        </property>
        <bag name="owners">
            <key>
                <column name="FAVORITE_MAKE_ID" />
            </key>
            <one-to-many class="Owners" />
        </bag>
    </class>
</hibernate-mapping>

Some problems here:

  • Any kind of collection mapping (set, list, bag, array, map) require a key element be defined.
  • The key generates an error because it doesn’t map the “same number of columns” (i.e. it needs 2 columns to match the 2 column primary key). It’s saying it needs another key defined.
  • So why not just get rid of the primary key? Because the class element requires a id or composite-id element. And we can’t make just MAKE_ID or MODEL_ID the primary key because those won’t be unique.

Solution

At long last! For Owners → Vehicles, this actually works.

Owners.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>
    <class name="Owners" table="OWNERS">
        <id name="ownerId" type="int">
            <column name="OWNER_ID" />
            <generator class="assigned" />
        </id>
        <property name="favoriteMakeId" type="int">
            <column name="FAVORITE_MAKE_ID" />
        </property>
        <property name="name" type="string">
            <column name="NAME" length="20" />
        </property>
        <set name="vehicles" inverse="false">
            <key property-ref="favoriteMakeId" column="MAKE_ID" />
            <one-to-many class="Vehicles" />
        </set>
      </class>
</hibernate-mapping>

There still doesn’t appear to be any method to properly associate Vehicles → Owners, but thankfully the mapping file above is all I really need for my case.

There also doesn’t appear to be any way to produce a mapping file like this using Hibernate Tools reverse engineering, so I just have to make it manually.

Going back through some of the many links I visited while searching for help, I noticed this page also basically explains the solution above.

Tuesday, April 28, 2009

How to build Hibernate Core...I think?

Checkout the lastest SVN trunk from http://anonsvn.jboss.org/repos/hibernate/core/trunk.
I got rev 16450

Set your JAVA_HOME environment variable to a Java 5 JDK (it fails with Java 6).
Mine is set to C:\Program Files\Java\jdk1.5.0_17

Edit parent/pom.xml to add these lines in bold.

...
         </mailingList>
     </mailingLists>


    <repositories>
        <repository>
            <id>jboss</id>
            <url>http://repository.jboss.com/maven2/</url>
        </repository>

        <repository>
            <id>jboss-snapshot</id>
            <url>http://snapshots.jboss.org/maven2</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>jboss</id>
            <url>http://repository.jboss.com/maven2/</url>
        </pluginRepository>
    </pluginRepositories>


     <build>
         <plugins>
             <plugin>
...

Download Maven.
I got apache-maven-2.1.0-bin.zip

Unpack Maven somewhere, cd to the hibernate-core trunk directory and run this command.

<path to apache-maven>/bin/mvn package

This should automatically download everything, build the whole thing, and run the tests.

My test results were

Tests run: 117, Failures: 0, Errors: 56, Skipped: 0

At this point I have no idea what to do…

Monday, April 20, 2009

Comparison of Hibernate with Netbeans and Eclipse

Netbeans 6.5.1 with Hibernate Support plugin 1.0.3

Update: Looks like the new Netbeans 6.7 has really improved Hibernate reverse-engineering support.

Netbeans’s Hibernate implementation is pleasantly simple, however its reverse-engineering is currently incomplete. If you want a straight-forward introduction to Java and Hibernate, Netbeans is the perfect way to go. But as soon as you want more powerful visual reverse-engineering tools, you’d best switch to Eclipse.

Steps to use Hibernate in Netbeans

  • Add Hibernate Support plugin
  • Setup a database connection in the Services window
  • Create a new Java Application project
  • Create a new Hibernate Configuration File (hibernate.cfg.xml)
    • Select the database connection
    • press Finish
  • Edit the hibernate.cfg.xml and add these properties
    hibernate.show_sql = true # under Configuration Properties (optional)
    hibernate.current_session_context_class = thread # under Miscellaneous Properties
  • Create new “Hibernate Mapping Files and POJOs from Database”
    • select the configuration file
    • choose the tables to reverse engineer
    • check “JDK 5 Language Features” to get type-safe generics
    • select a package where reverse engineered classes will go
    • press Finish
  • Create new “HibernateUtil.java”
    • So Hibernate can find the configuration file even if it’s in the jar, I recommend changing the line
      sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

      to

      URL cfgurl = HibernateUtil.class.getResource("hibernate.cfg.xml");
      sessionFactory = new AnnotationConfiguration().configure(cfgurl).buildSessionFactory();

There’s currently no way to regenerate the reverse-engineered code once it’s been generated. This thread says it is “targeted as part of the next release” (Netbeans 6.7 in June '09).

Eclipse 3.4.2 with Hibernate Tools addon 3.2.4

Is it just me, or is it really hard to find up-to-date information on the web about setting up Hibernate in Eclipse? There is one tutorial that doesn’t seem too old, and covers most of my steps listed below.

Being new to Eclipse, it might be difficult to figure out there are actually 2 different addons you can download: Hibernate Tools, and Hibernate Synchronizer (last release 3 years ago?). There’s also MyEclipse that costs money but probably makes the whole process more seamless. To get started in Eclipse, it might be useful to understand how Eclipse does Java.

There are 4 different configurations to be aware of for Eclipse Hibernate Tools:

  1. The Configuration file (hibernate.cfg.xml), used by the Console Configuration (technically optional because most if not all of these settings can be made in the Console Configuration)

  2. The Console Configuration, used when creating the Reverse Engineering file, and by the Hibernate Code Generation configuration

  3. The Reverse Engineering file (hibernate.regeng.xml) used by the Hibernate Code Generation configuration

  4. The Hibernate Code Generation configuration

So with plain Eclipse, here’s how you setup Hibernate Tools.

  • Find the URL to the Eclipse Hibernate Tool addon
  • Add the site to the Software Updates and install the addon
  • Find all the libraries necessary to use Hibernate in your program and download them
  • Create a new Java Project
    • under the Libraries tab, add all those Hibernate libraries
  • Open up the project properties
    • in Hibernate Settings, check “Enable Hibernate 3 support”
  • Create a new Hibernate Configuration file (hibernate.cfg.xml)
    Note that this configuration file is only to be used by the Console Configuration
    • select database dialect
    • select driver class
    • enter the connection URL
    • check “Create a console configuration”
    • press Finish
  • Edit the hibernate.cfg.xml and add these properties
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.show_sql">true</property>  <!-- optional -->
  • Create a new Hibernate Reverse Engineering file
    • select the Console Configuration you just made and press Refresh
    • select which tables to reverse engineer
  • Create a new Hibernate Code Generation configuration
    • select the Console Configuration
    • select the Output Directory (if the output directory contains your hibernate.cfg.xml, it will be overwritten by this task)
    • check “Reverse Engineer from JDBC Connection”
    • enter the regeng.xml file you created
    • under Exporters tab
      • check “Use Java 5 syntax” to get type-safe generics
      • check the following Exporters: Domain code, Hibernate XML Mappings, Hibernate XML Configuration
    • press Run
  • At this point your original Hibernate Configuration file could be replaced by the new one created by the Code Generation, or you can keep them separate
  • There’s no HibernateUtil generator, but all you really need is this
    URL cfgurl = this.getClass().getResource("hibernate.cfg.xml");
    SessionFactory sf = new AnnotationConfiguration().configure(cfgurl).buildSessionFactory();

In my specific case, I’m using Oracle 10g and the tables are in a schema named anotherschema. There are some things to watch out for.

  • Add the Oracle jdbc driver jar to your project libraries.
  • Case sensitivity!

Netbeans:

  • Add the schema to the database connection properties after it’s created (this also means each schema needs a separate connection).
  • Has a problem that prevents me from reverse-engineering a database more than once without restarting the IDE (error says table “cannot be added because it does not have a primary key”).

Eclipse:

  • Most places that need to read or refresh the database schema will often freeze Eclipse.

Friday, April 10, 2009

A fine transform

Spent a day trying to figure out why this function worked…

void transformDraw(BufferedImage bi,
                   Stroke st, Color c,
                   AffineTransform at, Shape sh)
{
    Graphics2D g2d = bi.createGraphics();
    g2d.setStroke(st);
    g2d.seteColor(c);
    g2d.draw(at.createTransformedShape(sh));
}

…but this one…

void transformDraw(BufferedImage bi,
                   Stroke st, Color c,
                   AffineTransform at, Shape sh)
{
    Graphics2D g2d = bi.createGraphics();
    g2d.setStroke(st);
    g2d.seteColor(c);
    g2d.transform(at);
    g2d.draw(sh);
}

…always resulted in the BufferedImage being filled entirely with the stroke color when I called the function like this…

transformDraw(myBufferedImg,
              new BasicStroke(3), Color.RED,
              AffineTransform.getScaleInstance(100000, 100000),
              myShape);

It was this pdf that helped me finally understand why those two functions are different.