hibernate實(shí)現(xiàn)有兩種配置,xml配置與注釋配置。
(1):xml配置:hibernate.cfg.xml (放到src目錄下)和實(shí)體配置類(lèi):xxx.hbm.xml(與實(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:3306/hxj
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<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 -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<!—update也可以用create/create-drop/update/validate代替, create 表示可以根據(jù)實(shí)體配置文件來(lái)自動(dòng)生成表(只能生成表).
-->
<property name="hbm2ddl.auto">update</property>
// 實(shí)體配置類(lèi)
<mapping resource="com/wsw/struts/model/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
(2): 實(shí)體配置類(lèi):xxx.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package=”com.wsw.struts.model”>
<class name="Person" table="per">
<id name="id" column="id">
<generator class="native"/> //字段自增
</id>
<property name="username" column="p_username"/>
<property name="age" column="p_age"/>
</class>
</hibernate-mapping>
(3):測(cè)試類(lèi)(包括獲取SessionFactory類(lèi)和實(shí)體測(cè)試類(lèi))
SessionFactory類(lèi):HibernateUtil
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
實(shí)體測(cè)試類(lèi):PersonManager
-----------------------------------------------------------------------------------
public class PersonManager {
public static void main(String[] args) {
createAndStorePerson();
HibernateUtil.getSessionFactory().close();
}
private static void createAndStorePerson() {
Session session = // 通過(guò)Session工廠(chǎng)獲取Session對(duì)象
HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction(); //開(kāi)始事務(wù)
Person person = new Person();
person.setUsername("何小景");
person.setAge(26);
session.save(person);
session.getTransaction().commit(); // 提交事務(wù)
}
}
(4):注解方式:
注解的方式與xml很很多類(lèi)似:
首先是需要加入4個(gè)jar包:hibernate-commons-annotations.jar 、 hibernate-annotations.jar
ejb3-persistence.jar 、 hibernate-jpa-2.0-api-1.0.1.Final.jar
下面是不同的地方:
(1):hibernate.hbm.xml 文件中把引用:xxx.hbm.xml改為引用實(shí)體類(lèi):
即把:<mapping resource="com/wsw/hibernate/model/Person.hbm.xml"/>
改為:<mapping class="com.wsw.hibernate.model.Teacher" />
(2):獲取SessionFactory方式發(fā)生了變化:
即:由SessionFactory sf = new Configuration().configure().buildSessionFactory()
改為:SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory()
(3):注解方式不需要在xxx.hbm.xml把實(shí)體類(lèi)與表進(jìn)行映射。而采用在實(shí)體類(lèi)中進(jìn)行注解。
注意:(1):如果實(shí)體類(lèi)屬性名與表字段名不一致的時(shí)候,要么都注解在屬性前,要么都注解在get方法前。不能部分注解在屬性前,部分注解在方法前。
(2):如果實(shí)體類(lèi)屬性名與表字段名一致的時(shí)候,可以部分注解在屬性前,部分注解在方法前。
(3):如果在實(shí)體類(lèi)中某些屬性不注解:(屬性和get都不寫(xiě)注解),默認(rèn)為表字段名與實(shí)體類(lèi)屬性名一致。
(4):如果實(shí)體類(lèi)的某個(gè)成員屬性不需要存入數(shù)據(jù)庫(kù)中,使用@Transient 進(jìn)行注解就可以了。即類(lèi)似于:(xxx.hbm.Xml配置中的某些字段不寫(xiě)(就是不需要對(duì)這個(gè)成員屬性進(jìn)行映射))
(5):表名稱(chēng)可以在實(shí)體類(lèi)前進(jìn)行注解。
(6):所有這些注解在:javax.persistence包下。而不是在hibernate包中。
---------------------------------------------------------------------------------------------------------------------
@Entity // 表示為實(shí)體類(lèi)
@Table(name="t_teacher") // 表名注解
public class Teacher implements Serializable {
private int id;
private String username;
private int age;
@Id // 表示主鍵
@GenericGenerator(name = "generator", strategy = "increment") @GeneratedValue(generator = "generator") // 自增長(zhǎng)
@Column(name = "id") // 類(lèi)屬性對(duì)應(yīng)著表字段
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="t_username") // 類(lèi)屬性對(duì)應(yīng)著表字段
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name="t_age") // 在實(shí)體類(lèi)屬性進(jìn)行注解,類(lèi)屬性對(duì)應(yīng)著表字段
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}