1、在mysql5中创建数据库 :
create database sigangjun_hibernate;
2、创建表DBUser:
use sigangjun_hibernate;
create table DBUser(
USER_ID int NOT NULL PRIMARY KEY,
USERNAME varchar(20) NOT NULL,
CREATED_BY varchar(20) NOT NULL,
CREATED_DATE date NOT NULL) type=innodb ;
3、打开POM.xml添加Hibernate的依赖。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.6.Final</version>
</dependency>
3、打开POM.xml添加mysql的依赖。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
其中pom.xml文件内容如下:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.sigangjun.architecture</groupId>
<artifactId>hibernate</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>hibernate Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.6.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>hibernate</finalName>
</build>
</project>
4.创建Hibernate映射文件(hbm)和Model类。创建新包cn.sigangjun.hibernate,并在包下添加如下文件。
DBUser.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>
<class name="cn.sigangjun.hibernate.DBUser" table="DBUser">
<id name="userId" type="java.lang.Integer">
<column name="USER_ID" />
<generator class="assigned" />
</id>
<property name="username" type="string">
<column name="USERNAME" length="20" not-null="true" unique="true" />
</property>
<property name="createdBy" type="string">
<column name="CREATED_By" length="20" not-null="true" unique="true" />
</property>
<property name="createdDate" type="date">
<column name="CREATED_DATE" length="7" not-null="true" />
</property>
</class>
</hibernate-mapping>
DBUser.java
package cn.sigangjun.hibernate;
import java.util.Date;
public class DBUser {
private Integer userId;
private String username;
private String createdBy;
private Date createdDate;
public DBUser() {
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Override
public String toString() {
return super.toString();
}
}
HibernateUtil.java
package cn.sigangjun.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
public static SessionFactory buildSessionFactory() {
try {
return new Configuration().configure().buildSessionFactory();
} catch (Throwable e) {
System.out.println("initial SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
App.java
package cn.sigangjun.hibernate;
import java.util.Date;
import org.hibernate.Session;
public class App {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
DBUser user = new DBUser();
user.setUserId(2);
user.setUsername("AA");
user.setCreatedBy("system");
user.setCreatedDate(new Date());
session.save(user);
session.getTransaction().commit();
}
}
5.创建Hibernate配置文件
创建一个Hibernate配置文件"hibernate.cfg.xml”,并将它放到资源目录的根目录下,"src/main/resources/hibernate.cfg.xml”,并填写相应的MySQL数据库信息。
<?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.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sigangjun_hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="cn/sigangjun/hibernate/DBUser.hbm.xml" />
</session-factory>
</hibernate-configuration>
6.运行App.java,将会插入一条新的记录到“DBUser”表
十月 17, 2013 4:42:40 下午 org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
十月 17, 2013 4:42:40 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.6.Final}
十月 17, 2013 4:42:40 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
十月 17, 2013 4:42:40 下午 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
十月 17, 2013 4:42:40 下午 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
十月 17, 2013 4:42:40 下午 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
十月 17, 2013 4:42:40 下午 org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
十月 17, 2013 4:42:40 下午 org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: cn/sigangjun/hibernate/DBUser.hbm.xml
十月 17, 2013 4:42:40 下午 org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
十月 17, 2013 4:42:40 下午 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
十月 17, 2013 4:42:40 下午 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
十月 17, 2013 4:42:40 下午 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
十月 17, 2013 4:42:40 下午 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
十月 17, 2013 4:42:40 下午 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/sigangjun_hibernate]
十月 17, 2013 4:42:40 下午 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
十月 17, 2013 4:42:41 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
十月 17, 2013 4:42:41 下午 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
十月 17, 2013 4:42:41 下午 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into DBUser (USERNAME, CREATED_By, CREATED_DATE, USER_ID) values (?, ?, ?, ?)
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:838]