Hibernate4入门教程:Hello World!
来源:互联网 发布:始祖鸟羽绒服 知乎 编辑:程序博客网 时间:2024/05/22 03:08
一、配置hibernate.cfg.xml文件中的属性自动提示功能
1、 配置如下图,将http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd放入第三步的文本框中
二、HelloWorld
2、 在 http://sourceforge.net/projects/hibernate/files/hibernate4/下载hibernate-release-4.2.4.Final.zip
3、 创建一个普通的java项目,在根目录下创建一个名称为“lib”的文件夹用来存放导入的jar包.
4、 选择hibernate必须的jar包导入项目,将下载的hibernate-release-4.2.4.Final.zip解压开,选择hibernate-release-4.2.4.Final\lib\required下面的所有jar包。
5、 Hibernate的jar包导入之后就需要导入mysql的驱动包
6、 在src目录下创建hibernate的配置文件hibernate.cfg.xml,步骤如下:
a) 在项目名称上右键【New】->【other】,选择Hibernate Configuration file,然后【Next>】
b) 默认名字就叫【hibernate.cfg.xml】,然后直接【Finish】就可以了
Hibernate.cfg.xml配置文件的内容如下
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEhibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 配置连接数据库的基本信息 -->
<propertyname="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<propertyname="hibernate.connection.username">root</property>
<propertyname="hibernate.connection.password">allyroot</property>
<propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- Hibernate的基本信息 -->
<!-- Hibernate使用的方言 -->
<propertyname="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<!-- 是否在控制台打印sql -->
<propertyname="show_sql">true</property>
<!-- 是否格式化sql -->
<propertyname="format_sql">true</property>
<!-- 自动生成数据表的策略 -->
<!-- create:会根据.hbm.xml文件生成新的数据表,每次都会删除上一次的表,重新生成表 create-drop:会根据.hbm.xml文件生成新的数据表,但SessionFactory一关闭,表就自动删除
update:最常用的属性,会根据.hbm.xml文件生成新的数据表,若.hbm.xml文件和数据表中对应的数据表结构不不同,Hibernate会更新数据表结构,但不会删除已经有的列和行
validate:会和数据表进行比较,若.hbm.xml文件中的列在数据表中不存在,则抛出异常 -->
<propertyname="hbm2ddl.auto">update</property>
<!-- 指定映射的 .hbm.xml文件 -->
<mappingresource="pojo/News.hbm.xml"/>
</session-factory>
</hibernate-configuration>
7、 在src下创建pojo包,并创建News.java类,代码如下
package pojo;
import java.util.Date;
public class News {
private Integerid;
private Stringtitle;
private Stringcontent;
private Datetime;
public Integer getId() {
returnid;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
returntitle;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
returncontent;
}
public void setContent(String content) {
this.content = content;
}
public Date getTime() {
returntime;
}
public void setTime(Date time) {
this.time = time;
}
public News() {
}
public News(String title, String content, Date time) {
super();
this.title = title;
this.content = content;
this.time = time;
}
@Override
public String toString() {
return"News [id=" + id +", title=" + title +", content=" + content +", time=" + time +"]";
}
}
8、 根据pojo生成对应的hbm.xml配置文件步骤如下:
a) 在pojo包上右键【New】->【other】,选择Hibernate XML Mapping file,然后【Next>】
b) 选择要生成实体类的包,直接【Finish】就可以生成对应的hbm.xml文件
c) 生成对应的hbm.xml文件信息如下:
<?xmlversion="1.0"?>
<!DOCTYPEhibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2015-3-27 18:21:31 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<classname="pojo.News"table="NEWS"lazy="false">
<idname="id"type="java.lang.Integer">
<columnname="ID"/>
<generatorclass="native"/>
</id>
<propertyname="title"type="java.lang.String">
<columnname="TITLE"/>
</property>
<propertyname="content"type="java.lang.String">
<columnname="CONTENT"/>
</property>
<propertyname="time"type="java.util.Date">
<columnname="TIME"/>
</property>
</class>
</hibernate-mapping>
9、 在src下创建test包,用来写测试方法,代码如下
a) 新增:
package test;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Test;
import pojo.News;
public class Insert {
@Test
public void testName() throws Exception {
SessionFactory sessionFactory = null;
Configuration configuration = new Configuration().configure();
// Hibernate 的任何配置都需要在serviceRegistry中注册之后才有效
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// 4.0之前的创建方式
// sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
// 开启事务
Transaction transaction = session.beginTransaction();
News news = new News("新闻","内容",new Date());
try {
session.save(news);
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
}
session.close();
sessionFactory.close();
}
}
注意:
1、由于Hibernate.cfg.xml中hbm2ddl.auto这个配置的是“update”,所以不需要创建数据库表,程序会在运行的时候自动根据*.hbm.xml文件自动创建数据库表,至于如何从数据库表中生成对应的*.hbm.xml配置文件会在以后的博客中写出。
2、Test类中的test()方法在运行的时候需要选择JUnitTest方式,同时还需要将JUnit的包引入项目中,这里就不在描述如何引入JUnit包的方法了。
b) 查询:
package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import pojo.News;
public class Query {
private SessionFactory sessionFactory;
private Sessionsession;
private Transactiontransaction;
@Before
public void init() {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
@After
public void destory() {
transaction.commit();
session.close();
sessionFactory.close();
}
@Test
public void test() {
News news = (News) session.get(News.class, 1);
System.out.println(news.getContent());
}
}
c) 修改:
package test;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Test;
import pojo.News;
public class Update {
private SessionFactorysessionFactory;
private Sessionsession;
private Transactiontransaction;
@Test
public void test() throws Exception {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
News news = (News) session.get(News.class, 3);
news.setContent("内容1");
news.setTime(new Date());
// session.update(news);
session.update(news);
transaction.commit();
session.clear();
sessionFactory.close();
}
}
d) 删除:
package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Test;
import pojo.News;
public class Delete {
private SessionFactorysessionFactory;
private Sessionsession;
private Transactiontransaction;
@Test
public void test() throws Exception {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.delete(session.get(News.class, 1));
transaction.commit();
session.close();
sessionFactory.close();
}
}
- Hibernate4入门教程:Hello World!
- vb入门教程-第一章HELLO WORLD
- PHP快速入门教程:hello world
- Struts2入门教程-Hello World
- [andorid系列]Hello world入门教程
- cocos2d入门教程4 : Hello World
- Struts2入门教程-Hello World!
- golang入门教程(一) Hello World
- ExtJs 入门教程二[Hello World]
- PHP Lumen - 入门教程 - hello world
- Python入门教程一:Hello World
- RabbitMQ入门教程【1】-Hello World
- RabbitMQ入门教程(三):Hello World
- Struts入门教程 - 第1章 Hello World
- JavaFx中文入门教程--从Hello World开始
- RabbitMQ入门教程 For Java【1】 - Hello World
- 无废话ExtJs 入门教程二[Hello World]
- Vert.x入门教程之Hello World
- Linux-(7)归档、压缩
- 机器学习(三)k均值聚类
- android drawable selector
- Java与C++在面象对象基本概念上的区分
- 寻找最近点对
- Hibernate4入门教程:Hello World!
- C# 读写文件的方法汇总
- 禁用部分radio(实践)
- goldengate 检查点的理解
- js数据类型
- C#文件处理
- 二元关系
- matlab将jpg图片转成avi视频
- 简要说明RFID系统的时隙ALOHA算法的工作过程