Hibernate,一個O/R Mapping產品,入門非常輕易,今天才開始看,做了個例子。貼出來大家參考!
環境如下:
開發的IDE:JBuilderX
使用的數據庫:My Sql 4.0
使用的數據庫驅動:MySQL JDBC Driver
1.JBX下建立WEB應用程序hib.jpx。
2.PRoject Properties->Paths->Required Libraries->add->new 這里定義hibernate的類庫 把hibernate的lib下面的所有jar包進去 當然還有hibernate2.jar也要;new定義mysql把MySQL JDBC Driver的jar包進去。
2、在屬性里的Required Libraries里加入hibernate和mysql;
3.建立相應文件,其具體結構如下:
---hib
-----hib(下面文件自動生成)
-----src
-----hib
-----Create.java (建立person表)
-----Insert.java (向person表插入記錄)
-----Person.java
-----mysql.txt (person表SQL腳本)
-----Person.hbm.xml(映射文件)
-----hibernate.properties (從hibernate的src下面找到,要進行修改)
-----log4j.properties (從hibernate的src下面找到)
4.原文件如下:
Create.java
package hib;
import net.sf.hibernate.session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaEXPort;
/**
*本類只是用來創建表的,并不往表內部插入任何數據,并且只能使用一次,否則會刪除已有的表的
*/
public class Create
{
private static SessionFactory sessionFactory;
public static void main(String[] args) throws Exception
{
Configuration conf = new Configuration().addClass(Person.class);
//第一次運行時用來在數據庫中創建表
//并且把sql語句輸出到txt文件用的
//以后的運行不能使用該段代碼,否則每次都會先刪除原表,再新建該表
SchemaExport dbExport = new SchemaExport(conf);
dbExport.setOutputFile("mysql.txt");
dbExport.create(true, true);
}
}
Insert.java
package hib;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
|
新聞熱點
疑難解答