1、环境:
Maven :3.1.1
开发工具:Spring Tool Suite
数据库 : Mysql 5.6
2、项目文件结构
文件代码:
2.1 、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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hibernate</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
2.2 、HibernateUtil.java
package com.rhythmk.hibernate01;
import javax.imageio.spi.ServiceRegistry;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
/*
* 参考 URL:
* http://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html_single/
* */
public class HibernateUtil {
// By : rhythmk.cnblogs.com
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration=new Configuration().configure();
return configuration.buildSessionFactory(new ServiceRegistryBuilder().applySettings(configuration.getProperties()).build());
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
2.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">
<!-- 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/shishuocms</property>
<property name="connection.username">root</property>
<property name="connection.password">wangkun</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property>
<!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于差错,程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。项目部署后可以设置为false,提高运行效率 -->
<property name="hibernate.show_sql">true </property>
<mapping resource="com/rhythmk/model/user.hbm.xml" />
</session-factory>
</hibernate-configuration>
2.4 User.java
package com.rhythmk.model;
import java.util.Date;
public class User {
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getOpenId() {
return openId;
}
public void setOpenId(Integer openId) {
this.openId = openId;
}
@Override
public String toString() {
return "User [userId=" + userId + ", openId=" + openId + ", type="
+ type + ", name=" + name + ", createTime=" + createTime + "]";
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer userId;
public Integer openId;
public String type;
public String name;
public Date createTime;
}
2.5 user.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="com.rhythmk.model.User" table="user">
<id name="userId" type="int">
<column name="userId" />
<generator class="native" />
</id>
<property name="openId" type="int">
<column name="openId" not-null="true" />
</property>
<property name="type" type="string">
<column name="type" not-null="true" />
</property>
<property name="name" type="string">
<column name="name" length="45" not-null="true" />
</property>
<property name="createTime" type="timestamp">
<column name="createTime" not-null="true" />
</property>
</class>
</hibernate-mapping>
3、测试代码(hibernatedemo1.java):
插入:
@Test
public void InsertUser() {
SessionFactory sessionfac = HibernateUtil.getSessionFactory();
Session session = null;
org.hibernate.Transaction tran = null;
try {
sessionfac.openSession();
User entity = new User();
tran = session.beginTransaction();
entity.setType("管理员");
entity.setName("rhythmk");
entity.setOpenId(1);
entity.setCreateTime(new Date());
session.save(entity);
tran.commit();
System.out.println("Insert into OK!");
} catch (Exception e) {
if (tran != null) {
tran.rollback();
}
e.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
修改:
@Test
public void UpdateUser() {
Session session = null;
org.hibernate.Transaction tran = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tran = session.beginTransaction();
User entity = (User) session.load(User.class, 2);
entity.setName("Update");
session.save(entity);
tran.commit();
entity = (User) session.load(User.class, 2);
System.out.println(entity.toString());
} catch (Exception e) {
if (tran != null) {
tran.rollback();
}
// TODO: handle exception
e.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
删除:
@Test
public void DelUser() {
Session session = null;
org.hibernate.Transaction tran = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tran = session.beginTransaction();
Object obj = session.load(User.class, 4);
User entity = null;
if (obj != null) {
entity = (User) obj;
}
if (entity != null) {
session.delete(entity);
System.out.println("删除成功!");
tran.commit();
}
} catch (Exception e) {
if (tran != null) {
tran.rollback();
}
// TODO: handle exception
e.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
单对象查询
@Test
public void SelectUser() {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
User entity = (User) session.load(User.class, 2);
System.out.println(entity.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
List查询
@Test
public void SelectListUser() {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
Query query= session.createQuery("from User ");
List<User> list=(List<User>)query.list();
for (User user : list) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
分页查询:
@Test
public void SelectPageListUser() {
// 获取分页数据
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
Query query= session.createQuery("from User ");
List<User> list=(List<User>)query
.setFirstResult(0) //从0项开始
.setMaxResults(3) //每页三条数据
.list();
for (User user : list) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
代码包:http://pan.baidu.com/s/1hq1esh2
备注:
添加 JBOOS TOOL路径
http://download.jboss.org/jbosstools/updates/stable/helios/