package tutego; import java.sql.SQLException; import com.j256.ormlite.dao.*; import com.j256.ormlite.db.HsqldbDatabaseType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.jdbc.JdbcConnectionSource; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.*; @DatabaseTable class Contact { @DatabaseField( generatedId = true ) Long id; @DatabaseField String name; // Setter/Getter sparen } public class ORMLiteDemo { public static void main( String[] args ) { System.setProperty( "tutegoHsqldbDatabasePath", "TutegoDB" ); String url = "jdbc:hsqldb:file:${tutegoHsqldbDatabasePath};shutdown=true"; ConnectionSource connectionSource; try { connectionSource = new JdbcConnectionSource( url, "sa", "", new HsqldbDatabaseType() ); Dao<Contact, String> dao = DaoManager.createDao( connectionSource, Contact.class ); // TableUtils.createTable( connectionSource, Contact.class ); Contact c1 = new Contact(); c1.name = "Chris"; dao.create( c1 ); Contact c2 = new Contact(); c2.name = "Juvy"; dao.create( c2 ); Contact c3 = dao.queryForId( "1" ); System.out.println( c3.name ); connectionSource.close(); } catch ( SQLException e ) { e.printStackTrace(); } } }
1. Klassen annotieren mit den ORMLite-Annotationen oder mit JPA-Annotationen
2. Sind die Tabellen nicht da, muss man TableUtils.createTable( connectionSource, Contact.class ); aufrufen, dann erzeugt ORMLite die Tabellen.
3. Der Rest ist einfach, siehe Beispiel 🙂
Mehr unter http://ormlite.com/.