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

Hibernate demo之使用xml的更多相关文章

  1. 基本hibernate DEMO

    Hibernate常用API: 1Configuration: 负责加载主配置文件信息,同时也加载映射关系文件信息. 2SessionFactory 负责创建Session对象. 3Session 数 ...

  2. eclipse hibernate配置文件(*.hbm.xml)加上自动提示功能

    转自:https://blog.csdn.net/u012217085/article/details/17397843?utm_source=blogkpcl3 1. 标签:hibernate 在编 ...

  3. Hibernate demo之使用注解

    1.新建maven项目 testHibernate,pom.xml <?xml version="1.0" encoding="UTF-8"?> & ...

  4. MyEclipse10中自动生成Hibernate的实体和xml配置文件

    前提:1.在项目中添加Hibernate支持 2.MyEclipse中已经创建好数据库连接 3.表已经建好并且有主键 步骤如下: 1.在DB Browser窗口的已打开连接节点中选中用户创建的所有的表 ...

  5. hibernate ——helloWorld程序(XML配置)

    1.项目结构 2.hibernate实现了Java类 和 数据库表的映射(Map) 先看一下Student的Java类和对应的数据库表 package com.pt.hibernate; public ...

  6. spring,hibernate配置事务 beans.xml

    beans.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="htt ...

  7. Hibernate注解配置与XML配置区别

    注解配置的方式与xml很很多类似: 首先是需要加入4个jar包:hibernate-commons-annotations.jar . hibernate-annotations.jar.ejb3-p ...

  8. eclipse中hibernate和mybatis中xml配置文件的没有标签提醒解决方法

    当我们使用eclipse编写Mybatis或hibernate的xml文件时,面对众多标签的配置文件,却没有自动提醒,对于工作和学习都十分不方便. 之所以没有自动提醒,是因为dtd文件没有加载成功. ...

  9. intellij配置hibernate自动生成hbm.xml文件

    1.首先创建一个Java web项目,这里因为已经在整个项目中配置好tomcat了,所以我是直接创建module的,其实和创建project的配置方法一样,创建的时候选择Web Application ...

随机推荐

  1. 【HDOJ5519】Kykneion asma(状压DP,容斥)

    题意:给定n和a[i](i=0..4),求所有n位5进制数中没有前导0且i出现的次数不超过a[i]的数的个数 2<=n<=15000,0<=a[i]<=3e4 思路:设f(n, ...

  2. js常用方法 备用

    /* function obj$(id)                      根据id得到对象 function val$(id)                      根据id得到对象的值 ...

  3. poj 2796 Feel Good dp || 单调栈

    题目链接 题意 对于一个长度为\(n\)的非负整数数列\(a_1,a_2,-,a_n\),求\(max_{1≤l≤r≤n}f(l,r)\), 其中 \[f(l,r)=min(a_l,a_{l+1},- ...

  4. 《Linux命令行与shell脚本编程大全 第3版》Linux命令行---32

    以下为阅读<Linux命令行与shell脚本编程大全 第3版>的读书笔记,为了方便记录,特地与书的内容保持同步,特意做成一节一次随笔,特记录如下:

  5. i2c 协议解析【转】

    转自:http://blog.csdn.net/g_salamander/article/details/8016698 版权声明:本文为博主原创文章,未经博主允许不得转载. 1.基本概念 主机    ...

  6. Qualcomm download 所需要的 contents.xml

    Platform MSM8917 PM8937 PMI8940 在 Qualcomm code base 中, amss下有許多 MSM89xx 之類的 folder, 這些是為了不同 chip 所產 ...

  7. 关于URL编码 [转]

    转自: http://www.ruanyifeng.com/blog/2010/02/url_encoding.html 作者: 阮一峰 日期: 2010年2月11日 一.问题的由来 URL就是网址, ...

  8. C#Qrcode生成二维码支持中文,带图片,带文字

    C#Qrcode生成二维码支持中文带图片的操作请看二楼的帖子,当然开始需要下载一下C#Qrcode的源码 下载地址 : http://www.codeproject.com/Articles/2057 ...

  9. window postgresql 10.4安装

    window installer下载地址:https://www.enterprisedb.com/downloads/postgres-postgresql-downloads 其他版本官网下载地址 ...

  10. 通过ansible一键部署集群ntp时间同步

    环境准备 [root@server ~]# cat /etc/redhat-release CentOS Linux release (Core) [root@server ~]# uname -r  ...