近日,​​Persistence4j 1.1​​版本发布了,它是一个小型、轻量级的Java 对象持久层类库,实现关系数据库和Java 对象之间的持久化。此版本主要是对bug的修复,点击查看更新详情:​​http://code.google.com/p/persistence4j/​

Persistence4j的目标就是开发一款操作简单使用方便的Java ORM框架,秉承这一设计理念设计出的Persistence4j拥有及其简单的配置,其语法基于​​JDK 1.6​​中的注释,使用起来十分方便。

实例代码:

  1. //First lets create a simple pojo which you like to persist.  
  2. @Entity(schema="library",table="book")  
  3. public class Book{  
  4. @Column(isPrimaryKey=true)  
  5. private String isbn;  
  6. @Column  
  7. private String title;  
  8. @Column  
  9. private int authorid;  
  10. public Book(){  
  11.  
  12. }  
  13. public Book(String isbn, String title, int authorid){  
  14.   this.isbn = isbn;  
  15.   this.title = title;  
  16.   this.authorid = authorid;  
  17. }  
  18. // getters  
  19. }  
  20.  
  21. DataProviderFactory dataProviderFactory = new DataProviderFactoryImpl(config);  
  22. String databaseName = "library";  
  23. String dbmsName = "mysql" 
  24. boolean isTransactional = false;  
  25. DataProvider dataProvider =  dataProviderFactory.getDataProvider(databaseName, dbmsName, isTransactional);  
  26.  
  27. // Now lets create a object of Book class and persist it  
  28. Book book = new Book("123432","TestBook",5);  
  29. TransferUtil.registerClass(Book.class);  
  30. GenericDAO<Book> genericDAO = new GenericDaoImpl<Book>(dataProvider.getDataFetcher());  
  31.  
  32. //Persist Book  
  33. genericDAO.createEntity(book);  
  34.  
  35. //Remove Book  
  36. genericDAO.deleteEntity(book);  
  37.  
  38. //Test if Entity Exists  
  39. genericDAO.isEntityExists(book);  
  40.  
  41. // findByPrimaryKey  
  42. Object obj[] = new Object[1];  
  43. obj[0] = "123432";  
  44. genericDAO.findByPrimaryKey(Book.class, obj);  
  45.  
  46. //If you want to use transactions.This how to get TransactionService.Make sure //isTransactional variable should be true and underlying dbms supports ACID.  
  47. TransactionService ts = dataProvider.getTransactionService();  
  48. try{  
  49.     ts.beginTransaction();  
  50.     genericDAO.createEntity(book);  
  51.     ts.commitTransaction();  
  52. }catch(Exception exp){  
  53. ts.rollbackTransaction();  
  54. }  
  55.  
  56. // Check the GenericDAO interface for all the available methods..  
  57. You can extend GenericDAOImpl and override the methods and add your own methods.