Persistence4J - Java对象持久化
jopen
12年前
Persistence4j 是一个非常简单的类库,用于持久化数据至关系数据库中。它个类库可以不需要数据传输对象。只需创建一个POJO,然后利用这个类库简单的保存。这个类库还集成了Java transaction API。支持的数据库包括:Apache Derby ;H2 Database ;HSQLDB ;MySQL ;PostgreSQL。
//First lets create a simple pojo which you like to persist. @Entity(schema="library",table="book") public class Book{ @Column(isPrimaryKey=true) private String isbn; @Column private String title; @Column private int authorid; public Book(){ } public Book(String isbn, String title, int authorid){ this.isbn = isbn; this.title = title; this.authorid = authorid; } // getters } DataProviderFactory dataProviderFactory = new DataProviderFactoryImpl(config); String databaseName = "library"; String dbmsName = "mysql" boolean isTransactional = false; DataProvider dataProvider = dataProviderFactory.getDataProvider(databaseName, dbmsName, isTransactional); // Now lets create a object of Book class and persist it Book book = new Book("123432","TestBook",5); TransferUtil.registerClass(Book.class); GenericDAO<Book> genericDAO = new GenericDaoImpl<Book>(dataProvider.getDataFetcher()); //Persist Book genericDAO.createEntity(book); //Remove Book genericDAO.deleteEntity(book); //Test if Entity Exists genericDAO.isEntityExists(book); // findByPrimaryKey Object obj[] = new Object[1]; obj[0] = "123432"; genericDAO.findByPrimaryKey(Book.class, obj); //If you want to use transactions.This how to get TransactionService. //Make sure isTransactional variable should be true and underlying dbms supports ACID. TransactionService ts = dataProvider.getTransactionService(); try{ ts.beginTransaction(); genericDAO.createEntity(book); ts.commitTransaction(); }catch(Exception exp){ ts.rollbackTransaction(); } // Check the GenericDAO interface for all the available methods.. You can extend GenericDAOImpl and override the methods and add your own methods.