读过<<深入浅出Hibernate>> 了解到 ORM,系统设计分层思想,现在仅对Hibernate(4.1.4)这一持久层实现框架的使用作笔录以备忘之.
基本概念
1.Hibernate 是一种“对象——关系数据映射组件”,它使用映射文件将对象(Object)与关系型数据(Relational)相关联。在Hibernate中,映射文件通常以.hbm.xml作为后缀。
2.Configuration 负责管理Hibernate的DB配置信息,如url,username等,
一般Configuration configuration = new Configuration().configure();这样创建,默认下会在类路径下找hibernate.cfg.xml或者hibernate.properties配置文件读取配置信息。
若不想取用默认方式读取配置,可以这样:
File f = new File("yourpath\\yourfilename.xml");
Configuration configuration = new Configuration().configure(f);
3.获取configuration只为创建sessionFactory,从Ver.4之后这样创建:
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory 会根据configuration当前的配置被构建,之后对configuration的任何变更将不会到已创建的sessionFactory,sessionFactory的创建代价高昂,系统设计中应充分考虑重用,sessionFactory线程安全,所以一般针对一个数据库共享一个sessionFactory。
4.Session, Hibernate完成增删改查的核心所在,session非线程安全。
Ver.4之后session创建有两种方式:
getCurrentSession()与openSession()
* 采用getCurrentSession()创建的session会绑定到当前线程中,而采用openSession()
创建的session则不会
* 采用getCurrentSession()创建的session在commit或rollback时会自动关闭,而采用openSession()创建的session必须手动关闭,顾名思义,此方法必须使用于session已在早前创建的情形下,否则报错
使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property>
此处盗用一下别人的图,联结上述:
O/R映射——hibernate之核心所在(个人观点)。
数据类型映射:
1)hibernate基本数据类型,仅附上一表以查阅:
Java数据类型
|
Hibernate数据类型
|
标准SQL数据类型
(PS:对于不同的DB可能有所差异) |
byte、java.lang.Byte
|
byte
|
TINYINT
|
short、java.lang.Short
|
short
|
SMALLINT
|
int、java.lang.Integer
|
integer
|
INGEGER
|
long、java.lang.Long
|
long
|
BIGINT
|
float、java.lang.Float
|
float
|
FLOAT
|
double、java.lang.Double
|
double
|
DOUBLE
|
java.math.BigDecimal
|
big_decimal
|
NUMERIC
|
char、java.lang.Character
|
character
|
CHAR(1)
|
boolean、java.lang.Boolean
|
boolean
|
BIT
|
java.lang.String
|
string
|
VARCHAR
|
boolean、java.lang.Boolean
|
yes_no
|
CHAR(1)('Y'或'N')
|
boolean、java.lang.Boolean
|
true_false
|
CHAR(1)('Y'或'N')
|
java.util.Date、java.sql.Date
|
date
|
DATE
|
java.util.Date、java.sql.Time
|
time
|
TIME
|
java.util.Date、java.sql.Timestamp
|
timestamp
|
TIMESTAMP
|
java.util.Calendar
|
calendar
|
TIMESTAMP
|
java.util.Calendar
|
calendar_date
|
DATE
|
byte[]
|
binary
|
VARBINARY、BLOB
|
java.lang.String
|
text
|
CLOB
|
java.io.Serializable
|
serializable
|
VARBINARY、BLOB
|
java.sql.Clob
|
clob
|
CLOB
|
java.sql.Blob
|
blob
|
BLOB
|
java.lang.Class
|
class
|
VARCHAR
|
java.util.Locale
|
locale
|
VARCHAR
|
java.util.TimeZone
|
timezone
|
VARCHAR
|
java.util.Currency
|
currency
|
VARCHAR
|
2)实体映射,本质就是实体类与数据库表之间的映射,简称类表映射,其包括以下三项:
a) 表名——类名映射
b) 主键映射
c) 字段映射
以下是简单的增删改查示例,DB是mysql,项目是maven构建,用了hibernate4.1.4Final版本
项目目录结构:
立刻打码如下:
1. mysql 建表sql
create table t_user ( id int(11) not null auto_increment, name varchar(80) not null default '', primary key (id) );
2.pom.xml(maven 项目,不知其所以者可先google一番,此处仅用作添加jar包资源)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>learnHibernate</groupId> <artifactId>learnHibernate</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>learnHibernate</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.1.4.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.1.4.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.1.4.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.15</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version> </dependency> </dependencies> </project>
3.hibernate.cfg.xml (各项参数需要根据阁下实际情况做相应变动)
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/hibernate </property> <property name="hibernate.connection.username"> root </property> <property name="hibernate.connection.password"> root </property> <property name="hibernate.show_sql"> true </property> <property name="hibernate.format_sql"> true </property> <!-- 配置C3P0 --> <property name="hibernate.connection.provider_class"> org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider </property> <property name="hibernate.c3p0.max_size">10</property> <property name="hibernate.c3p0.min_size">1</property> <property name="hibernate.c3p0.max_statements">3</property> <property name="hibernate.c3p0.timeout">30</property> <property name="hibernate.c3p0.acquire_increment">1</property> <property name="hibernate.c3p0.idle_test_periodt">10</property> <!-- 配置二级缓存 --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.use_query_cache">true</property> <!-- Hibernate4 这里和Hibernate3不一样 要特别注意!!!--> <property name="hibernate.cache.region.factory_class"> org.hibernate.cache.EhCacheRegionFactory </property> <!-- Hibernate3 --> <!-- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> --> <!-- 实体映射文件 --> <mapping resource="learnHibernate/bean/TUser.hbm.xml" /> </session-factory> </hibernate-configuration>
4.Tuser.java
package learnHibernate.bean; import java.io.Serializable; public class TUser implements Serializable{ private static final long serialVersionUID = -2983670695642662371L; private int id; private String name; 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; } }
5. Tuser.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="learnHibernate.bean"> <class name="TUser" table="t_user"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native"/> </id> <property name="name" column="name" type="java.lang.String"/> </class> </hibernate-mapping>
6. HibernateLocalUtil.java (用于获取sessionFactory对象)
package learnHibernate.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public final class HibernateLocalUtil { private static SessionFactory sessionFactory; private HibernateLocalUtil() { } static { try { Configuration configuration = new Configuration().configure("hibernate\\hibernate.cfg.xml"); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); }catch (Throwable e) { throw new ExceptionInInitializerError(e); } } public static SessionFactory getSessionFactory () { return sessionFactory; } }
7. TestCase.java
package learnHibernate; import java.io.Serializable; import java.util.List; import learnHibernate.bean.TUser; import learnHibernate.util.HibernateLocalUtil; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.junit.Test; public class TestCase { //@Test public void saveTUser() { SessionFactory sessionFactory = HibernateLocalUtil.getSessionFactory(); Session session = sessionFactory.openSession(); TUser t1 = new TUser(); t1.setName("Cancan"); Transaction tx = session.beginTransaction(); Serializable id = session.save(t1); tx.commit(); session.close(); System.out.println("id = " + id); } //@Test public void updateTUser() { TUser t1 = new TUser(); t1.setId(3); t1.setName("Maomao"); SessionFactory sessionFactory = HibernateLocalUtil.getSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.update(t1); tx.commit(); session.close(); } //@Test public void deleteTUser() { TUser t1 = new TUser(); t1.setId(4); SessionFactory sessionFactory = HibernateLocalUtil.getSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.delete(t1); tx.commit(); session.close(); } @Test public void selectAll() { SessionFactory sessionFactory = HibernateLocalUtil.getSessionFactory(); Session session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(TUser.class); List<TUser> list = criteria.list(); showList(list); } private void showList(List<TUser> list) { for(TUser t : list) { System.out.println(t.getId() + " -- " + t.getName()); } } }
7.忘了一个log4j.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> </appender> <logger name="com.hibernate" additivity="false"> <level value="info" /> <appender-ref ref="console" /> </logger> <logger name="com.mchange" additivity="false"> <level value="info" /> <appender-ref ref="console" /> </logger> <root> <level value="info" /> <appender-ref ref="console" /> </root> </log4j:configuration>
至此入门上手结束,对hibernate只得一个大体上的感受。。。
项目见附件处