Hibernate操作步驟
1.新建項(xiàng)目2.加jar包3.寫xml配置文件hibernate.cfg.xml4.寫log4j.PRoperties日志文件5.在MySQL數(shù)據(jù)庫中建student表6.建Student實(shí)體類(先建表后建類)7.寫XML映射文件Student.hbm.xml,或者Annotation映射語句8.在hibernate.cfg.xml中添加相應(yīng)mapping9.寫測試類main,或者Junit測試類(項(xiàng)目右鍵-->“New”-->“Junit Test Case”)
HelloWorld小程序----XML映射文件
1.新建項(xiàng)目
2.加jar包。此處列出的jar包是Hibernate所需的全部jar包,在此項(xiàng)目中并不是全部需要
將如下jar包封裝進(jìn)一個(gè)User Library,名為hibernateantlr-2.7.6.jarc3p0-0.9.1.jarcommons-collections-3.1.jardom4j-1.6.1.jarhibernate3.jarhibernate-annotations.jarhibernate-commons-annotations.jarhibernate-jpa-2.0-api-1.0.0.Final.jarjavassist-3.12.0.GA.jarjta-1.1.jarjunit-4.10.jarlog4j-1.2.14.jarmysql-connector-java-5.1.7-bin.jarslf4j-api-1.6.1.jarslf4j-log4j12-1.6.1.jar
3.hibernate.cfg.xml配置文件。其中<mapping/>在步驟8中設(shè)置
<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/test</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool 連接池 --> <!-- <property name="connection.pool_size">1</property> --> <!-- SQL dialect 方言--> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 當(dāng)前session上下文 . thread:當(dāng)前線程;jta:(java transaction api) --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache 去掉二級緩存 --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout 顯示sql語句--> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup 常用選項(xiàng):create和update --> <property name="hbm2ddl.auto">update</property> <mapping resource="com/hibernate/model/Student.hbm.xml"/> <!-- <mapping class="com.hibernate.model.Student"/> --> </session-factory></hibernate-configuration>
4.log4j.properties日志文件
### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file hibernate.log ####log4j.appender.file=org.apache.log4j.FileAppender#log4j.appender.file.File=hibernate.log#log4j.appender.file.layout=org.apache.log4j.PatternLayout#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=warn, stdout#log4j.logger.org.hibernate=info#log4j.logger.org.hibernate=debug### log HQL query parser activity#log4j.logger.org.hibernate.hql.ast.AST=debug### log just the SQL#log4j.logger.org.hibernate.SQL=debug### log JDBC bind parameters ####log4j.logger.org.hibernate.type=info#log4j.logger.org.hibernate.type=debug### log schema export/update ####log4j.logger.org.hibernate.tool.hbm2ddl=debug### log HQL parse trees#log4j.logger.org.hibernate.hql=debug### log cache activity ####log4j.logger.org.hibernate.cache=debug### log transaction activity#log4j.logger.org.hibernate.transaction=debug### log JDBC resource acquisition#log4j.logger.org.hibernate.jdbc=debug### enable the following line if you want to track down connection ###### leakages when using DriverManagerConnectionProvider ####log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace5.在數(shù)據(jù)庫中建表
建表可以在數(shù)據(jù)庫中手動建,也可以通過運(yùn)行程序自動建立。
此處自動建表
6.建Student實(shí)體類
public class Student {private int id;private String name;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}7.Student.hbm.xml映射文件
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="com.hibernate.model.Student" dynamic-update="true"><id name="id"><generator class="native"></generator> <!-- generator設(shè)置其id自增 --></id> <!-- id指的是相應(yīng)表的主鍵 --><property name="name"></property><property name="age"></property></class></hibernate-mapping>
8.在hibernate.cfg.xml中添加相應(yīng)mapping
9.寫測試類main
public class StudentTest {public static void main(String[] args) {Student s = new Student();s.setName("s3");s.setAge(10);SessionFactory sf = new Configuration().configure().buildSessionFactory();Session session = sf.getCurrentSession();session.beginTransaction();session.save(s);session.getTransaction().commit();sf.close();}}程序到此結(jié)束,運(yùn)行后,會自動在數(shù)據(jù)庫創(chuàng)建student表,并將對象s存入student表中。
HelloWorld小程序----Annotation映射語句
步驟1-5同上
6,7.建實(shí)體類,添加Annotation注解
@Entity //表示這是一個(gè)實(shí)體類,和數(shù)據(jù)庫中的某個(gè)表是對應(yīng)的public class Teacher {private int id;private String name;private int age;@Id //主鍵@GeneratedValue //ID生成策略,默認(rèn)為AUTOpublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}8.在hibernate.cfg.xml中添加相應(yīng)mapping,如下
<mapping class="com.hibernate.model.Student"/>
9.寫測試類
測試類有很多種方式
a)見上文測試類main
b)創(chuàng)建一個(gè)HibernateUtil輔助類 ,然后再建測試類main
public class HibernateUtil {private static SessionFactory sf = buildSessionFactory();private static SessionFactory buildSessionFactory() {return new Configuration().configure().buildSessionFactory();}public static SessionFactory getSessionFactory() {return sf;}}
public class StudentTest {public static void main(String[] args) {Student s = new Student();s.setName("lisi");s.setAge(18);SessionFactory sf = HibernateUtil.getSessionFactory();Session session = sf.getCurrentSession();session.beginTransaction();session.save(s);session.getTransaction().commit();sf.close();}}c)建Junit測試類
項(xiàng)目右鍵-->“New”-->“Junit Test Case”,輸入類名,然后完善test方法
public class StudentTest_Junit {private static SessionFactory sf = null;@BeforeClasspublic static void beforeClass(){sf = new Configuration().configure().buildSessionFactory();}@AfterClasspublic static void afterClass(){sf.close();}@Testpublic void test() {Student s = new Student();s.setName("wangwu");s.setAge(23);Session session = sf.getCurrentSession();session.beginTransaction();session.save(s);session.getTransaction().commit();}}程序到此結(jié)束,運(yùn)行后,會自動在數(shù)據(jù)庫創(chuàng)建student表,并將對象s存入student表中。
新聞熱點(diǎn)
疑難解答
圖片精選