`

H2简单使用(配合hibernate)

 
阅读更多

在看一些教程,偶尔看到H2,被其精简的安装(只有一个jar包就好了..根本不用安装啊...)和完善的功能吸引了.

 

也做了一个很简单的东西,因为嫌写配置文件麻烦,所以就木有引spring进来了(这个我也是为了写教程里一个示例程序搭一下的 教程里直接JDBC然后写SQL 我这里加入一个hibernate 内容很简单 说错了欢迎指正呢)

 

环境:

 

h2-1.3.169

hibernate 3.6.10

 

项目结构如下:



 

 

先说下hibernate的配置文件:

<!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>
	    <!-- 驱动位置 -->
	    <property name="connection.driver_class">org.h2.Driver</property>
	    <!-- 存放位置 我这边放在了h盘下h2目录的product 会在相应位置生成一个.h2文件-->
        <property name="connection.url">jdbc:h2:h:/h2/product</property>
        <!-- 用户名 下面是密码 -->
        <property name="connection.username">sa</property>
        <property name="connection.password">sa</property>
        <!-- 使用的数据库方言 -->
         <property name="dialect">org.hibernate.dialect.H2Dialect</property>
		<property name="show_sql">true</property>
		<property name="hbm2ddl">update</property>
		<property name="current_session_context_class">thread</property>
		<!-- 引入的实体 -->
		<mapping class="org.cc.ws.entity.Product"/>
	</session-factory>
</hibernate-configuration>

 

接下去是实体类的文件:

package org.cc.ws.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;


@Entity
public class Product {

	@Id
	@GeneratedValue
	@Column(name="id")
	private int id;
	
	@Column(unique=true,nullable=false)
	private String name;
	
	private double price;
	
	private Date createTime;
	
	private int count;
	
	private String manufacturer;
	
	private String phoneNumber;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public String getManufacturer() {
		return manufacturer;
	}

	public void setManufacturer(String manufacturer) {
		this.manufacturer = manufacturer;
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	@Override
	public String toString() {
		return "Product [id=" + id + ", name=" + name + ", price=" + price
				+ ", createTime=" + createTime + ", count=" + count
				+ ", manufacturer=" + manufacturer + ", phoneNumber="
				+ phoneNumber + "]";
	}
	
	
}

 

然后利用SchemaExport来生成一下数据库:

package org.cc.ws.utils;

// 省略下引包

public class ExportDB {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//默认读取hibernate.cfg.xml文件.....
		Configuration cfg=new Configuration().configure();
		
		SchemaExport export=new SchemaExport(cfg);
		
		export.create(true, true);
	}

}

 正常的话 会出现下面的语句(show_sql选项打开的话):

写道
drop table Product if exists
create table Product (id integer generated by default as identity, count integer not null, createTime timestamp, manufacturer varchar(255), name varchar(255) not null unique, phoneNumber varchar(255), price double not null, primary key (id))

 

 

好了 接下去的操作就很简单了

像平常使用hibernate一样

发一下Dao的实现类:

package org.cc.ws.dao.impl;

// 省略引包

public class ProductDaoImpl implements ProductDao {

	@Override
	public boolean insert(Product product) {
		Session session=FactoryHolder.getSessionFactory().getCurrentSession(); 
		Transaction tas=session.beginTransaction();
		try{
		 product.setCreateTime(new Date());
		 session.save(product);
		 tas.commit();
		}catch(Exception e){
			e.printStackTrace();
			tas.rollback();
			return false;
		}
		return true;
	}

	@Override
	public Product getByName(String name) {
		Session session=FactoryHolder.getSessionFactory().getCurrentSession(); 
		Transaction tas=session.beginTransaction();
		Product product=null;
		try{
		  Query query=session.createQuery("from Product t where t.name=:name");
		  query.setString("name", name);
		  product=(Product) query.uniqueResult();
		  tas.commit();
		}
		catch(Exception e){
			tas.rollback();
			e.printStackTrace();
		}
			
		return product;
	}

	@Override
	public List<Product> getByManufacture(String manufacturer) {
		Session session=FactoryHolder.getSessionFactory().getCurrentSession(); 
		Transaction tas=session.beginTransaction();
		List<Product> products=null;
		try{
		  Query query=session.createQuery("from Product t where t.manufacturer=:manufacturer");
		  query.setString("manufacturer", manufacturer);
		  products=(List<Product>) query.list();
		  tas.commit();
		}
		catch(Exception e){
			tas.rollback();
			e.printStackTrace();
		}
			
		return products;
	}

}

 

 最后是一个测试文件:

package org.cc.ws.dao.impl;

import org.cc.ws.dao.ProductDao;
import org.cc.ws.entity.Product;

import junit.framework.TestCase;

public class ProductDaoTest extends TestCase{
	private ProductDao dao;
	public void setUp(){
		dao=new ProductDaoImpl();
		
	}
	public void testInsert(){
		Product product=new Product();
		product.setName("测试物品1");
		product.setManufacturer("cc");
		product.setPrice(10.0);
		dao.insert(product);
	}
	
	public void testName(){
		System.out.println(dao.getByName("测试物品1").getId());
	}
}

 执行第一个:

写道
Hibernate: insert into Product (id, count, createTime, manufacturer, name, phoneNumber, price) values (null, ?, ?, ?, ?, ?, ?)

 然后执行第二个:

写道
Hibernate: select product0_.id as id0_, product0_.count as count0_, product0_.createTime as createTime0_, product0_.manufacturer as manufact4_0_, product0_.name as name0_, product0_.phoneNumber as phoneNum6_0_, product0_.price as price0_ from Product product0_ where product0_.name=?
1

 可见使用正常.

 

  • 大小: 27.7 KB
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics