Persistence4J - Java對象持久化

jopen 11年前發布 | 14K 次閱讀 持久層框架 persistence4j

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.</pre>

項目主頁:http://www.baiduhome.net/lib/view/home/1357789000855

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!