devloop icon
Metastores

Reverse mapping tutorial

This tutorial shows you how to map an existing database table to a Java class

First, we assume that we have the following existing schema (shown here in MySQL 5):

	mysql> DESCRIBE Two;
	+-------+--------------+------+-----+---------+-------+
	| Field | Type         | Null | Key | Default | Extra |
	+-------+--------------+------+-----+---------+-------+
	| a     | varchar(255) | YES  | UNI | NULL    |       |
	| b     | tinyint(1)   | YES  |     | NULL    |       |
	+-------+--------------+------+-----+---------+-------+
	
	mysql> SELECT * FROM Two;
	+---------+------+
	| a       | b    |
	+---------+------+
	| string1 |    1 |
	| string2 |    0 |
	| string3 |    1 |
	+---------+------+
	1 row in set (0.00 sec)


To create this schema and some records in MySQL, we used:

	CREATE  TABLE Two (a VARCHAR(255) UNIQUE, b BOOL);
	INSERT INTO Two VALUES('string1', true);
	INSERT INTO Two VALUES('string2', false);
	INSERT INTO Two VALUES('string3', true);
	

Then we define a Java class to represent these records:

	@TableName("Two")
	public class Two {
		@ColumnName("a")
		public	String	a;
		@ColumnName("b")
		public	boolean	b;
	}
download source
Note the use of annotations to explicitly set the name of the table and its columns. The automatic mapping, as shown in the simple mapping tutorial may or may not have used the same values.

The table and its data can then be accessed using a simple command line program:

	DBDataMapper dbm = new DBDataMapper();
	dbm.checkApplication(Two.class);
	Collection<Two> objectsRead = IOHelper.readAll(Two.class);
	for (Two two : objectsRead) {
		System.out.println(two.a+" "+two.b);
	}
download source

Running this program produces the following output:

	QueryUtil(testdb[0])    getPreparedStatement(SELECT a,b FROM Two)
	string1 true
	string2 false
	string3 true

Related Links