星空网 > 软件开发 > Java

Hibernate 零配置之Annotation注解

  JPA规范推荐使用Annotation来管理实体类与数据表之间的映射关系,从而避免同时维护两份文件(Java 实体类 和

  以下我将使用eclipse来构建一个简单使用注解取代*.hbm.

1.在数据库中构建一张表

Hibernate 零配置之Annotation注解

 

2.生成相应的hibernate.cfg.Hibernate 零配置之Annotation注解Hibernate 零配置之Annotation注解

<?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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>    <property name="hibernate.connection.password">root</property>    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/zzh</property>    <property name="hibernate.connection.username">root</property>    <property name="show_sql">true</property>    <property name="hbm2ddl.auto">update</property>  </session-factory></hibernate-configuration>

View Code

注意,在生成cfg.

Hibernate 零配置之Annotation注解

Hibernate 零配置之Annotation注解

3.生成hibernate.reveng.Hibernate 零配置之Annotation注解Hibernate 零配置之Annotation注解

<?
View Code

在Eclipse界面工具栏,择Hibernate code generation Configuration,new 一个新的配置。

Hibernate 零配置之Annotation注解

4.选择Exporters的选项,接下来是重点!!!

Hibernate 零配置之Annotation注解

选择勾选的两项,不再选.hbm.

Hibernate 零配置之Annotation注解

点击Run。

5.只生成了与数据表对应的实体类Commodity.java,而没有生成与该实体类对应的映射文件Commodity.hbm.

package com.zzh;// Generated 2016-8-28 9:42:01 by Hibernate Tools 4.3.1.Finalimport javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import static javax.persistence.GenerationType.IDENTITY;import javax.persistence.Id;import javax.persistence.Table;/** * Commodity generated by hbm2java */@Entity@Table(name = "commodity", catalog = "zzh")public class Commodity implements java.io.Serializable {  private Integer id;  private String name;  private Double price;  private String unit;  private String category;  private String description;  private Integer seller;  public Commodity() {  }  public Commodity(String name, Double price, String unit, String category, String description, Integer seller) {    this.name = name;    this.price = price;    this.unit = unit;    this.category = category;    this.description = description;    this.seller = seller;  }  @Id  @GeneratedValue(strategy = IDENTITY)  @Column(name = "Id", unique = true, nullable = false)  public Integer getId() {    return this.id;  }  public void setId(Integer id) {    this.id = id;  }  @Column(name = "name", length = 100)  public String getName() {    return this.name;  }  public void setName(String name) {    this.name = name;  }  @Column(name = "price", precision = 11)  public Double getPrice() {    return this.price;  }  public void setPrice(Double price) {    this.price = price;  }  @Column(name = "unit", length = 50)  public String getUnit() {    return this.unit;  }  public void setUnit(String unit) {    this.unit = unit;  }  @Column(name = "category", length = 100)  public String getCategory() {    return this.category;  }  public void setCategory(String category) {    this.category = category;  }  @Column(name = "description", length = 1000)  public String getDescription() {    return this.description;  }  public void setDescription(String description) {    this.description = description;  }  @Column(name = "seller")  public Integer getSeller() {    return this.seller;  }  public void setSeller(Integer seller) {    this.seller = seller;  }}

使用@Entity注解,表示当前类为实体Bean,需要进行持久化,使用@Table注解实现数据表 commodity 与持久化类Commodity之间的映射,@Id注解指定当前持久化类的ID属性,使用@GeneratedValue注解指定ID表示生成器,使用@Column注解指定当前属性所对应的数据表中的字段,name指定字段名;unique指定是否为唯一,nullable指定是否可为null。

6.在hibernate.cfg.

  <mapping />

一定要注意mapping后面是class,如果是配置*.hbm.。

7.添加会话工厂类HibernateUtil以获取Session

Hibernate 零配置之Annotation注解Hibernate 零配置之Annotation注解
package com.zzh.utl;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.boot.registry.StandardServiceRegistry;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;public class HibernateUtil {  private static SessionFactory sessionFactory;  private static Session session;  static {    // 创建Configuration对象,读取hibernate.cfg.    Configuration config = new Configuration().configure();    StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()        .applySettings(config.getProperties());    StandardServiceRegistry ssr=ssrb.build();    sessionFactory=config.buildSessionFactory(ssr);  }    //获取SessionFactory  public static SessionFactory getSessionFactory(){    return sessionFactory;  }    //获取Session  public static Session getSession(){    session=sessionFactory.openSession();    return session;  }    //关闭Session  public static void closeSession(Session session){    if(session!=null){      session.close();    }  }}

View Code

8.用JUnit创建一个类ZhuShi.java用于测试

package anno;import static org.junit.Assert.*;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.junit.After;import org.junit.Before;import org.junit.Test;import org.hibernate.annotations.*;import com.zzh.Commodity;import com.zzh.utl.HibernateUtil;public class ZhuShi {  Session session = null;  @Before  public void setUp() throws Exception {    session = HibernateUtil.getSession();  }  @After  public void tearDown() throws Exception {    session.close();  }  @Test  public void test() {    String hql = " from Commodity ";    Query query = session.createQuery(hql);    List<Commodity> c = query.list();    for (Commodity commodity : c) {      System.out.println("name"+commodity.getName());    }  }}

9.整个文件已经形成

Hibernate 零配置之Annotation注解

运行测试,得到结果

Hibernate 零配置之Annotation注解

10.总结

  原来大量的*.hbm.

11.个人想法

  之前我有过不用注解后来因为路径调试半天的经历,那时自己也是笨,我就跟大家讲讲;我当时也是用反向工程生成实体类,还有*.hbm.

Hibernate 零配置之Annotation注解

 

由于是工具帮我生成的我也没在意,然后高高兴兴去配置cfg.

 

Hibernate 零配置之Annotation注解

全部文件如下所示:

Hibernate 零配置之Annotation注解

以为一切顺利,便用JUnit进行测试:

Hibernate 零配置之Annotation注解

实体类无法找到,坑爹呀,我都是按工具一步一步来的呀,为什么会这样,后来才发现*.hbm.

Hibernate 零配置之Annotation注解

再进行测试:

Hibernate 零配置之Annotation注解

  总算成功了,这不代表*.hbm.

  在这之后我会继续写一些关联映射的注释案例(比如双向一对多和双向多对多),如果你觉得还不错,请继续关注我或帮我点赞,谢谢观看!

                                                                                                                  ---参考资料《Struts2+Spring3+Hibernate框架技术精讲与整合案例》




原标题:Hibernate 零配置之Annotation注解

关键词:Hibernate

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

工具介绍:看Sellery’s SmartLists如何最大程度发挥Buy Box优势:https://www.ikjzd.com/articles/125714
亚马逊卖家故事:为什么黑五一天我的销售额可以破60万!:https://www.ikjzd.com/articles/12572
英国脱欧计划遭议会反对,将有取消退欧可能?:https://www.ikjzd.com/articles/12573
选品:亚马逊3C消费电子产品海外消费者画像:https://www.ikjzd.com/articles/125739
详解亚马逊上的三大促销利器:https://www.ikjzd.com/articles/125740
TikTok的For You推送机制解读:https://www.ikjzd.com/articles/125749
深圳到西安自驾路线攻略 深圳到西安自驾最佳路线:https://www.vstour.cn/a/411228.html
松花蛋是哪里的特产松花蛋的产地:https://www.vstour.cn/a/411229.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流