1.新建maven项目 testHibernate,pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>testHiberate</groupId>
<artifactId>testHiberate</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- 添加Hibernate依赖 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency> <!-- 添加Log4J依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.6.4</version>
</dependency> <!-- 添加javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.0.GA</version>
</dependency> <!-- mysql数据库的驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies> </project>

2.新建类Event

package com.demo;

import java.util.Date;

public class Event {

    private Long id;//id
private String title;//标题
private Date date;//日期
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}

3.在resource/mapper文件夹下新建Event.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.demo"> <class name="com.demo.Event" table="EVENTS"> <id name="id" column="EVENT_ID"> <generator class="assigned"/> </id> <property name="date" type="timestamp" column="EVENT_DATE"/> <property name="title"/> </class> </hibernate-mapping >

4.在resource文件夹下新建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">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.32.95:3306/db2</property>
<property name="connection.username">DB_WX_APP</property>
<property name="connection.password">LH_longfor</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.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 -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="mapper/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration>

5.新建辅助类 HibernateUtil

package com.demo;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class HibernateUtil { //定义静态的SessionFactory,产生单例,只生成一个SessionFactory
private static final SessionFactory sessionFactory = buildSessionFactory(); //用来初始化SessionFactory
private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
//得到SessionFactory
public static SessionFactory getSessionFactory() { return sessionFactory;//返回SessionFactory的对象 } }

6.新建Test类

package com.demo;

import java.util.Date;
import java.util.List; import org.hibernate.Session;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Test mgr = new Test();
//if (args[0].equals("store")) {
//mgr.createAndStoreEvent("My Event1", new Date());//调用函数插入数据
//}
mgr.getList();
// mgr.Get();//单个查询
HibernateUtil.getSessionFactory().close();
}
private void createAndStoreEvent(String title, Date theDate) { //得到目前运行的session
Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction();//开始事务
Event theEvent = new Event();//创建bean对象
theEvent.setTitle(title);//设置标题
theEvent.setId(100002L);
theEvent.setDate(theDate);//设置日期
session.save(theEvent);//保存对象
session.getTransaction().commit();//提交事务 } private void Get() { //得到目前运行的session
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();//创建bean对象
theEvent.setId(100001L);
Event e=(Event) session.get(Event.class,100001L);
System.out.println(e.getTitle());
session.getTransaction().commit(); } void getList(){
Session session=HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Event> list= session.createSQLQuery("select * from EVENTS").addEntity(Event.class).list();
for(Event e:list){ System.out.println(e.getTitle());
}
session.getTransaction().commit();
} }

运行Test类即可

https://pan.baidu.com/s/1fhnr4SWTkqd0RAdGniAMtA

最新文章

  1. 毕业设计 之 二 PHP学习笔记(一)
  2. HTML5Viewer中如何运行时绑定多数据源
  3. Android移动APP开发笔记——最新版Cordova 5.3.1(PhoneGap)搭建开发环境
  4. (转) Eclipse连接MySQL数据库(傻瓜篇)
  5. [工具类]文件或文件夹xx已存在,则重命名为xx(n)(2)
  6. AngularJS开发指南13:AngularJS的过滤器详解
  7. JVM基础:深入学习JVM堆与JVM栈
  8. bzoj3996
  9. jQuery事件绑定的最佳实践
  10. CAS 单点登录,通过ticket 获取登录用户
  11. 搭建C#框架 博文观感
  12. Flink资料(7) -- 背压监控
  13. 介绍一款基于jquery好用的编辑框htmlbox.full.js
  14. 学起来 —— CSS 入门基础
  15. CMake简介
  16. Hibernate从入门到了解
  17. elasticsearch简单实现
  18. Vue如何更新子组件
  19. Python制作二维码和条形码扫描器 (pyzbar)
  20. TensorFlow+Keras 02 深度学习的原理

热门文章

  1. ClassLoader 提供了两个方法用于从装载的类路径中取得资源:
  2. VMWare VMNet 8 的配置使用
  3. [AGC008F] Black Radius(树形dp)
  4. Docker(三):Docker的基本概念
  5. C++调用Matlab引擎 图像读写与处理 (知识+代码篇)
  6. 组合模式Composite Pattern(转)
  7. MOSFET 符號解說
  8. [Machine Learning with Python] Data Preparation through Transformation Pipeline
  9. Tallest Cow
  10. TCO 2015 Round 2A DIV1