(一)、Mysql:
第二部分的代码尤其重要,很多人在运行后会出现各种Bug,可以参见我上面的代码找出你的潜在的错误。
1、下图:左边是工程的总目录,右边是hibernate的jar包和JUnit的jar包:
2、各个文件的代码:
①、Gender.java为空;
②、Student.java代码:
package com.bjsxt.hibernate;
public class Student {
private String id;
private String name;
private int age;
public String getId() {
return id;
}
public void setId(String 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;
}
}
package com.bjsxt.hibernate;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
//实体类
@Entity
@Table(name="_Teacher")
public class Teacher {
private int id;
private String name;
private String title;
private Date birthDate;
@Temporal(TemporalType.DATE)
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="_name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.bjsxt.hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class TeacherTest {
public static void main(String[] args){
Teacher t = new Teacher();
t.setId(1);
t.setName("t1");
t.setTitle("高级");
t.setBirthDate(new Date());
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
}
}
<?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.bjsxt.hibernate">
<class name="Student">
<id name="id">
<generator class="uuid"></generator>
</id>
<property name="name"/>
<property name="age"/>
</class>
</hibernate-mapping>
⑤、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>
<!-- 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>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!--
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost :1521:SXT</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
-->
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<!-- 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="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/bjsxt/hibernate/Student.hbm.xml" />
<mapping class="com.bjsxt.hibernate.Teacher"/>
</session-factory>
</hibernate-configuration>
⑥、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{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=trace
package com.bjsxt.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.bjsxt.hibernate.Student;
public class HibernateIDTest {
private static SessionFactory sessionFactory;
@BeforeClass
public static void beforeClass() {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
@AfterClass
public static void afterClass() {
sessionFactory.close();
}
@Test
public void testStudentSave() {
Student s = new Student();
s.setName("s1");
s.setAge(21);
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
}
public static void main(String args[]) {
beforeClass();
}
}
3、运行结果:
在HibernateIDTest.java上点击Run As——JUnit Test,得到下图:
4、打开MySql命令提示符:
输入show tables;
select * from student;
得到下图的结果:
显示了生成的ID号,以及表的类型结构。
第二部分的代码尤其重要,很多人在运行后会出现各种Bug,可以参见我上面的代码找出你的潜在的错误。
如有意见,欢迎斧正。
在XML里生成ID,用generator标签,常见的四个取值:native,identity,sequence,uuid,
如果要想让程序跨数据库平台,应当选择native或uuid;
(二)、Oracle:
1、导入classes12.jar包,oracle连接的驱动;
2、在目录:F:\Tools\hibernate-distribution-3.3.2.GA-dist\project\etc\hibernate.properties,找到Oracle的相关配置文件:
(上面是MySql的,下面是Oracle的)
修改
3、运行后生成结果:
运行结果大家可以再pl/sql或者oracle里查看。