1、笔记
主要增加:
D:\Java\SSH\Tools\log4j-1.2.17.jar
D:\Java\SSH\Tools\slf4j-log4j12-1.7.4.jar
取得properties文件:
D:\Java\SSH\hibernate-4.1.10\project\etc
要保证hibernate包中没有slf4j的jar
自己屏蔽的内容有:
#log4j.logger.org.hibernate=debug
#log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.tool.hbm2ddl=debug
把这个打开,可以看到创建表单的内容
log4j.logger.org.hibernate.tool.hbm2ddl=debug
junit
创建一个source folder
2、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
3、hibernate.cfg.xml
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">haizhu</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</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.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup:创建或者修改表 -->
<!-- 一共有create,update,validate,create-drop 四个模式 -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/haizhu/model/Student.hbm.xml"/>
<mapping class="com.haizhu.model.Teacher"/>
</session-factory>
</hibernate-configuration>
4、HibernateSessionFactory.java
package com.haizhu.hb;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
5、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>
<class name="com.haizhu.model.Student" table="h_student">
<id name="id" column="s_id" type="int">
<generator class="native"></generator>
</id>
<property name="name" column="s_name"/>
<property name="age" column="s_age"/>
</class>
</hibernate-mapping>
6、Student.java
package com.haizhu.model;
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、StudentTest.java
package com.haizhu.model;
import org.hibernate.Session;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import com.haizhu.hb.HibernateSessionFactory;
import com.haizhu.model.Student;
public class StudentTest {
Session sess = null;
@Before
public void setUp() throws Exception {
sess = HibernateSessionFactory.getSession();
System.out.println("增加学生:");
}
@Test
public void test() {
Student s = new Student();
s.setId(22);
s.setName("刘克会");
s.setAge(25);
sess.beginTransaction();
sess.save(s);
sess.getTransaction().commit();
sess.close();
}
@AfterClass
public static void afterClass(){
System.out.println("程序顺利结束!");
}
}
8、Teacher.java
package com.haizhu.model;
import java.util.Date;
import javax.persistence.*;
@Entity
@Table(name= "h_teacher")
public class Teacher {
private int id;
private String name;
private String title;
private String yourwifename;
private Date date;
private Sex sex;
/**
* @Id 映射主键属性,这里采用uuid的主键生成策略
* @GeneratedValue —— 注解声明了主键的生成策略。该注解有如下属性
* strategy 指定生成的策略,默认是GenerationType. AUTO
* GenerationType.AUTO 主键由程序控制
* GenerationType.TABLE 使用一个特定的数据库表格来保存主键
* GenerationType.IDENTITY 主键由数据库自动生成,主要是自动增长类型
* GenerationType.SEQUENCE 根据底层数据库的序列来生成主键,条件是数据库支持序列
* generator 指定生成主键使用的生成器
*
* 更改主键为自增长:alter table A modify column a not null auto_increment;
*
*/
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name="name")
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;
}
@Transient
public String getYourwifename() {
return yourwifename;
}
public void setYourwifename(String yourwifename) {
this.yourwifename = yourwifename;
}
@Temporal(TemporalType.DATE)
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Enumerated(EnumType.STRING)
public Sex getSex() {
return sex;
}
public void setSex(Sex sex) {
this.sex = sex;
}
}
9、Sex.java
package com.haizhu.model;
public enum Sex {
man,lady
}
10、TeacherTest.java
package com.haizhu.model;
import java.util.Date;
import com.haizhu.hb.*;
import com.haizhu.model.Teacher;
import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;
public class TeacherTest {
@Before
public void setUp() throws Exception {
System.out.println("增加老师:");
}
@Test
public void test() {
Teacher t = new Teacher();
t.setId(15);
t.setName("海竹");
t.setTitle("甲");
t.setYourwifename("小丽");
t.setDate(new Date());
t.setSex(Sex.man);
Session sess = HibernateSessionFactory.getSession();
sess.beginTransaction();
sess.save(t);
sess.getTransaction().commit();
}
}