hibernate是什么就不说了 这里就说怎么用吧
一、首先建工程,然后导入以下几个基本包(1是hibernate基本包,2是hibernate-annotation包,3是mysql数据库包):
1: hibernate3.jar (hibernate3的核心包)
antlr-2.7.6.jar (语言转换工,Hibernate利用它实现 HQL 到 SQL的转换)
commons-collections-3.1.jar (Apache Commons 包中的一个,包含了一些Apache开发的集合类,功能比java.utils.*功能强大,必须使用的jar)
dom4j-1.6.1.jar (dom4j是一个java的 XML API,类似于jdom,用来读写xml文件,这是必须的jar,Hibernate用它来读写配置文件,必须使用的jar)
javassist-3.9.0.GA.jar (语言转换工,Hibernate利用它实现 HQL 到 SQL的转换)
jta-1.1.jar (java Transaction API (JTA) 规范的包,是指定事务和事务处理和分布式事务处理系统之间的标准,JAVA接口,包括资源管理,应用服务,和事务应用程序。)
slf4j-api-1.5.8.jar 各种日志的接口
slf4j-log4j12-1.5.8.jar 使用slf4j对log4j日志的实现,也可以使用别的,替换了这个就行
log4j-1.2.14.jar log4j日志包
2. hibernate与annotation结合的包(如果用XML配置的话可以不用加):
ejb3-persistence.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
3. mysql-connector-java-5.1.18-bin.jar (链接mysql的驱动包)
二、在mysql数据库里建立数据库表
create database hibernate;
use hibernate;
create table student(id int,name varchar(20),age int);
三、建立Model(student)对象类
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;
}
}
四、接下来就是比较重要的hibernate配置文件了:
1.在src目录下(这是默认路径)建立hibernate.cfg.xml
2.从hibernate的文档里找到以下默认配置并粘贴
<?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>
<!-- Database connection settings 数据源配置-->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) 连接池 hibernate自带的连接池一般不用 项目开发中经常用到的是application server本身用JNDI注册在里面的连接池-->
<property name="connection.pool_size">1</property>
<!-- SQL dialect 数据库方言 有Oracle方言 mysql方言 sql_server方言等等 比如mysql分页用的是limit oracle分页用的是三层嵌套-->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Enable Hibernate's automatic session context management 事务管理 默认是thread(局部事务) 还可以用全局事务jta一般在多个不同数据库操作才用到-->
<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 hibernate自动生成建表语句-->
<property name="hbm2ddl.auto">update</property>
<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration><pre name="code" class="html">
3.更改配置信息如下:
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</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 -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/wy/model/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4.在student同目录下建立Student.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.wy.model">
<class name="Student" table="student" dynamic-update="true">
<id name="id" column="id">
</id>
<property name="name" />
<property name="age" />
</class>
</hibernate-mapping>
5.在src目录下建立log4j.properties日志配置文件:
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%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=trace
五、测试
1.建立测试类test,注意包别导错了:
package com.wy.common;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.wy.model.*;
public class StudentTest {
public static void main(String[] args) {
Student s=new Student();
s.setId(1);
s.setName("wy");
s.setAge(24);
Configuration cfg=new Configuration();//获取hibernate配置信息,默认在src下找hibernate.cfg.xml
SessionFactory sf=cfg.configure().buildSessionFactory();//构建session工厂(线程安全,资源占用大)
Session session=sf.openSession();//产生一个session(线程不安全,占用资源少)
<span style="white-space:pre"> </span>//openSession永远产生一个新的session;getCurrentSession()如果上下文有则使用原有的session,没有的话再产生一个新的session;
session.beginTransaction();//开启事务管理
session.save(s);//存入内存
session.getTransaction().commit();//同步数据库,持久化(也就是存入数据库)
session.close();//关闭session
sf.close();//关闭session工厂
}
}
2.run as JAVA APPLICATION 成功;
10:09:14,959 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:155 - Running hbm2ddl schema update
10:09:14,961 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:167 - fetching database metadata
10:09:14,962 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:179 - updating schema
10:09:14,982 INFO org.hibernate.tool.hbm2ddl.TableMetadata:65 - table found: hibernate.student
10:09:14,982 INFO org.hibernate.tool.hbm2ddl.TableMetadata:66 - columns: [id, age, name]
10:09:14,982 INFO org.hibernate.tool.hbm2ddl.TableMetadata:68 - foreign keys: []
10:09:14,982 INFO org.hibernate.tool.hbm2ddl.TableMetadata:69 - indexes: []
10:09:14,983 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:217 - schema update complete
Hibernate: insert into student (name, age, id) values (?, ?, ?)
六、现在使用annotation配置:
1.建立model(Teacher)类:
package com.wy.model;
import java.util.Date;
import javax.persistence.*;
@Entity
public class Teacher {
private int id;
private String name;
private String title;
@Id
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 String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
需要注意的是@Entity 是实体类 ,@Id是主键
2.在hibernate.cfg.xml配置文件里加上类的引入:
<mapping class="com.wy.model.Teacher"/>
注意:teacher类用的是annotation,用了annotation就不用Teacher.cfg.xml;student用的XML配置用以下,注意区别
<mapping resource="com/wzy/model/Student.hbm.xml"/>
3.创建数据库teacher表:
create table teacher(id int,name varcher(20),title varcher(20));
4.创建测试类:
package com.wy.common;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import com.wy.model.*;
public class StudentTest {
public static void main(String[] args) {
Teacher s=new Teacher();
s.setId(4);
s.setName("wy");
s.setTitle("中级");
Configuration cfg=new AnnotationConfiguration();
SessionFactory sf=cfg.configure().buildSessionFactory();
Session session=sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
sf.close();
}
}
注意:new的是AnnotationConfiguration();
5.run as JAVA APPLICATION 成功;
10:46:40,137 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:155 - Running hbm2ddl schema update
10:46:40,138 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:167 - fetching database metadata
10:46:40,139 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:179 - updating schema
10:46:40,158 INFO org.hibernate.tool.hbm2ddl.TableMetadata:65 - table found: hibernate.teacher
10:46:40,158 INFO org.hibernate.tool.hbm2ddl.TableMetadata:66 - columns: [id, title, name]
10:46:40,158 INFO org.hibernate.tool.hbm2ddl.TableMetadata:68 - foreign keys: []
10:46:40,158 INFO org.hibernate.tool.hbm2ddl.TableMetadata:69 - indexes: []
10:46:40,171 INFO org.hibernate.tool.hbm2ddl.TableMetadata:65 - table found: hibernate.student
10:46:40,172 INFO org.hibernate.tool.hbm2ddl.TableMetadata:66 - columns: [id, age, name]
10:46:40,172 INFO org.hibernate.tool.hbm2ddl.TableMetadata:68 - foreign keys: []
10:46:40,172 INFO org.hibernate.tool.hbm2ddl.TableMetadata:69 - indexes: [primary]
10:46:40,173 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:217 - schema update complete
Hibernate: insert into Teacher (name, title, id) values (?, ?, ?)