您的位置:首页 > 其它

Hibernate例子-自己写的一个干净的给予注解的Hibernate例子

2012-10-12 16:23 387 查看
我不喜欢说废话,因为我是菜鸟,要更认真!下面请看本人代码!

1.导包(图片说明,我把hibernate的注解包和hiberhate3.jar全部导入了,因为我怕出错)





2.写hibernat.cfg.xml(注意最好放在src根目录下)

<?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">

<hibernate-configuration>

<session-factory>

<!-- hibernate的数据库方言,这里是指mysql -->

<property name="dialect">

org.hibernate.dialect.MySQLDialect

</property>

<property name="connection.url">

jdbc:mysql://localhost:3306/testssh

</property>

<property name="connection.username">root</property>

<property name="connection.password">root</property>

<property name="connection.driver_class">

com.mysql.jdbc.Driver

</property>

<!-- 这个东西现在还不知道是干啥的不过留着 HibernateAnnotationTest指项目名称-->

<property name="myeclipse.connection.profile">

HibernateAnnotationTest/MySQL5.5

</property>

<property name="hibernate.hbm2ddl.auto">update</property> <!-- 开启hibernate自动创建sql -->

<!--<property name="format_sql">true</property> 以固定格式显示sql语句在控制台 -->

<!-- <property name="show_sql">true</property> 显示 sql语句在控制台 -->

<property name="current_session_context_class">thread</property><!-- 使用的是本地事务(jdbc事务) -->

<mapping class="com.model.Hiberuser" /><!-- 加载model -->

<mapping class="com.model.Product" />

<mapping class="com.model.Category" />

</session-factory>

</hibernate-configuration>

3.写一个创建SessionFactory的工具类

package com.utils;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.AnnotationConfiguration;

import org.hibernate.cfg.Configuration;

import org.hibernate.tool.hbm2ddl.SchemaExport;

public class HibernateConnection {

private static Configuration config = null;

public static SessionFactory sessionFactory = null;

static{

config = new AnnotationConfiguration();

config.configure("hibernate.cfg.xml");//hibernate.cfg.xml放在src根目录下

sessionFactory = config.buildSessionFactory();

/*SessionFactory sessionFactory = config.buildSessionFactory();

此为另一种获得sessionfactory的方式 */

SchemaExport schemaExport = new SchemaExport(config);

//create方法的两个参数第一个:自动创建table功能开启,第二个:新增的时候不是覆盖原有记录而是新增记录

schemaExport.create(true, false);

}

}

4.三个Model其中(Category与Product是一对多的关系,不过我个人觉得hibernate搞哪些关联对我们这些小项目来将纯属扯淡)

(1)Category 类

import java.util.HashSet;

import java.util.Set;

import javax.persistence.CascadeType;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.OneToMany;

import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

/**

* 类别对象,父表

* @author xiefeng

*/

//当前的类是一个持久化类,是Category这个类。他映射了一个表category。所对应的数据库是testssh//这句:@Table(name = "category", catalog = "testssh") 可以省略

@Entity

@Table(name = "category", catalog = "testssh")

public class Category implements java.io.Serializable {

private static final long serialVersionUID = 3240281547213597385L;

private Integer id;

private String name;

private String description;

//对于这个主表来讲,这个set其实主要是为了在查询中能够级联查询出附表信息

private Set<Product> products = new HashSet<Product>(0);

public Category() {

}

public Category(String name, String description, Set<Product> products) {

this.name = name;

this.description = description;

this.products = products;

} // 主键 :@Id 主键生成方式:strategy = "increment"

// 映射表中id这个字段,不能为空,并且是唯一的

@GenericGenerator(name = "generator", strategy = "increment")

@Id

@GeneratedValue(generator = "generator")

@Column(name = "id", unique = true, nullable = false)

public Integer getId() {

return this.id;

}

public void setId(Integer id) {

this.id = id;

}

// 映射表中name这个字段 ,长度是500

@Column(name = "name", length = 500)

public String getName() {

return this.name;

}

public void setName(String name) {

this.name = name;

}

// 映射表中description这个字段 ,长度是500

@Column(name = "description", length = 500)

public String getDescription() {

return this.description;

}

public void setDescription(String description) {

this.description = description;

}

// 级联操作:cascade = CascadeType.ALL

// 延迟加载:fetch = FetchType.LAZY

// 映射:mappedBy = "category"

// 一对多方式

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")

public Set<Product> getProducts() {

return this.products;

}

public void setProducts(Set<Product> products) {

this.products = products;

}

}

(2)Product类

package com.model;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.ManyToOne;

import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

/**

* 产品对象,子表

* @author xiefeng

*

*/

@Entity

@Table(name = "product", catalog = "testssh")

public class Product implements java.io.Serializable {

private static final long serialVersionUID = -1546206493725028472L;

private Integer id;

private Category category;//关联的父表

private String name;

private String price;

private String descripton;

public Product() {

}

public Product(Category category, String name, String price,

String descripton) {

this.category = category;

this.name = name;

this.price = price;

this.descripton = descripton;

}

@GenericGenerator(name = "generator", strategy = "increment")

@Id

@GeneratedValue(generator = "generator")

@Column(name = "id", unique = true, nullable = false)

public Integer getId() {

return this.id;

}

public void setId(Integer id) {

this.id = id;

}

// 延迟加载:多对一方式

// 关联信息:外键name = "category_id"

//optional=true 表示此字段可以为空,反之则然

@ManyToOne(fetch = FetchType.LAZY,optional=true)

@JoinColumn(name = "category_id")//指定关联父表的字段,数据表里为category_id

public Category getCategory() {

return this.category;

}

public void setCategory(Category category) {

this.category = category;

}

@Column(name = "name", length = 500)

public String getName() {

return this.name;

}

public void setName(String name) {

this.name = name;

}

@Column(name = "price", length = 10)

public String getPrice() {

return this.price;

}

public void setPrice(String price) {

this.price = price;

}

@Column(name = "descripton", length = 500)

public String getDescripton() {

return this.descripton;

}

public void setDescripton(String descripton) {

this.descripton = descripton;

}

}

(3)Hiberuser类(这个类只是一个干净的Model没有任何关联)

package com.model;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity

@Table(name = "hiberuser", catalog = "testssh")

public class Hiberuser implements java.io.Serializable{

private static final long serialVersionUID = 5228046410953157123L;

private Integer id;

private String name;

public Hiberuser(){

}

public Hiberuser(String name) {

this.name = name;

}

@GenericGenerator(name = "generator", strategy = "increment")

@Id

@GeneratedValue(generator = "generator")

@Column(name = "id", unique = true, nullable = false)

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

@Column(name = "name", length = 500)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

5.Main方法测说Hibernate

package com.test;

import java.util.List;

import java.util.Set;

import org.hibernate.Hibernate;

import org.hibernate.Query;

import org.hibernate.Session;

import com.model.Category;

import com.model.Hiberuser;

import com.model.Product;

import com.utils.HibernateConnection;

/**

* @author XH

* 测试hibernate常用操作数据库方法。

* 从下面的操作数据库方法我们可以看出,其实hibernate的全注解的中心是放在对象之间的映射配置上,而不是在操作数据库的方法上

*/

public class HibernateTest {

public static void main(String[] args) {

HibernateTest test = new HibernateTest();

test.addHiberuser();

test.addCategory();

test.addProduct();

test.findOneMany1();

test.findOneMany2();

String hql1 = "from Hiberuser";//注意这里Hiberuser是对象而不应是表

test.findByHql(hql1);

String hql2 = "update Hiberuser h set h.name= 'account2' where h.id=1";

test.updateByHql(hql2);

String hqlDelete = " delete from Hiberuser where id = 1";

test.updateByHql(hqlDelete);

test.findByHqlWenHao("sfdasdf");

test.findByHqlParameter("sfdasdf");

Hiberuser hiberuser = new Hiberuser();

hiberuser.setId(1);

hiberuser.setName("sfdasdf");

test.findByHqlObj(hiberuser);

}

public void addHiberuser() {

// 此getCurrentSession()方法不同与传统的.openSession(),它可以自动完成session的管理(开启和关闭)

Session session = HibernateConnection.sessionFactory.getCurrentSession();

session.beginTransaction();

Hiberuser user = new Hiberuser();

user.setName("account1");

session.save(user);// hibernate自带方法,插入对象到数据库

session.getTransaction().commit();

}

/**

* 一对多

*/

public void addCategory() {

Session session = HibernateConnection.sessionFactory.getCurrentSession();

session.beginTransaction();

Category gory = new Category();

gory.setName("食品类");

gory.setDescription("这个是放置食品的类!");

session.save(gory);// hibernate自带方法,插入对象到数据库

session.getTransaction().commit();

}

public void addProduct() {

Session session = HibernateConnection.sessionFactory.getCurrentSession();

session.beginTransaction();

Category c = (Category) session.get(Category.class, 1);// hibernate自带方法,通过id从数据库获得对象

Product p = new Product();

p.setName("计算机科学与技术2");

p.setPrice("234");

p.setDescripton("计算机科学与技术,好啊,真是红啊22");

p.setCategory(c);

c.getProducts().add(p);

session.save(p);// hibernate自带方法,插入对象到数据库

session.getTransaction().commit();

}

/**

* 一对多查询,查询主表并关联出附表

*/

public void findOneMany1() {

Session session = HibernateConnection.sessionFactory.getCurrentSession();

session.beginTransaction();

Category c = (Category) session.get(Category.class, 1);// hibernate自带方法,通过id从数据库获得对象

System.out.println("id: " + c.getId() + " name:" + c.getName());

Set<Product> p = c.getProducts();

for (Product product : p) {

System.out.println("id:" + product.getId() + " name:"

+ product.getName() + " description:"

+ product.getDescripton());

}

session.getTransaction().commit();

}

/**

* 一对多查询,查询附表关联出主表

*/

public void findOneMany2() {

Session session = HibernateConnection.sessionFactory.getCurrentSession();

session.beginTransaction();

Product p = (Product) session.get(Product.class, 3);

System.out.println(p.getName());

System.out.println("dd----" + p.getCategory().getDescription());

}

/**

* 自定义hql查询操作

*/

//简单查询列表

public void findByHql(String hql) {

Session session = HibernateConnection.sessionFactory.getCurrentSession();

session.beginTransaction();

Query query = session.createQuery(hql);

List<Hiberuser> users = query.list();

for (Hiberuser user : users) {

System.out.println(user.getName());

}

}

//匹配查询之问号匹配方法

public void findByHqlWenHao(String names) {

Session session = HibernateConnection.sessionFactory.getCurrentSession();

session.beginTransaction();

Query query = session.createQuery(" from Hiberuser h where h.name=?");

query.setString(0,names);

List<Hiberuser> users = query.list();

for (Hiberuser user : users) {

System.out.println(user.getName());

}

}

//匹配查询之setParameter方法--简单匹配

public void findByHqlParameter(String namestr) {

Session session = HibernateConnection.sessionFactory.getCurrentSession();

session.beginTransaction();

Query query = session.createQuery(" from Hiberuser h where h.name=:customname");

query.setParameter("customname", namestr, Hibernate.STRING);

//setParameter()方法包含三个参数,分别是命名参数名称,命名参数实际值,以及命名参数映射类型。对于某些参数类型 setParameter()方法可以更具参数值的Java类型,

//猜测出对应的映射类型,因此这时不需要显示写出映射类型,像上面的例子,可以直接这样写:

//query.setParameter(“customername”,namestr);但是对于一些类型就必须写明映射类型,比如 java.util.Date类型,因为它会对应Hibernate的多种映射类型,比如Hibernate.DATA或者 Hibernate.TIMESTAMP

List<Hiberuser> users = query.list();

for (Hiberuser user : users) {

System.out.println(user.getName());

}

}

//匹配查询之setParameter方法--对象做参数匹配

public void findByHqlObj(Hiberuser hiberuser) {

Session session = HibernateConnection.sessionFactory.getCurrentSession();

session.beginTransaction();

Query query = session.createQuery(" from Hiberuser h where h.name=:name and h.id=:id");

query.setProperties(hiberuser);

//setProperties()方法会自动将customer对象实例的属性值匹配到命名参数上,但是要求命名参数名称必须要与实体对象相应的属性同名。

List<Hiberuser> users = query.list();

for (Hiberuser user : users) {

System.out.println(user.getName());

}

}

/**

* 自定义hql修改,刪除操作

* @param hql

*/

public void updateByHql(String hql) {

Session session = HibernateConnection.sessionFactory.getCurrentSession();

session.beginTransaction();

Query query = session.createQuery(hql);

query.executeUpdate();

session.getTransaction().commit();

}

}

到此一个给予全注解的Hibernate简单例子完了,这里我觉得hibernate的全注解的中心是放在对象之间的映射配置上,而不是在操作数据库的方法上(自己学习用的,所以请高手多多指出错误)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  例子 注解 Hibernat