用Annotation 写ORM关联数据库表确实要简单很多(主要是可以省略一个配置文件),所以在Hibernate中都喜欢用Annotation

这个用例中有关于ID生成策略(所以用到了联合主键),和属性是否与数据库映射,以及DATE类型的精度问题·····

准备工作:

1.Hibernate 3.3.2 下载 https://www.hibernate.org/6.html

下载所需要的Hibernate jar包和Annotation jar 包(注意,这里有版本兼容问题)

Html代码 
  1. Package  Version  Core  Annotations  EntityManager  Validator  Search  Shards  Tools
  2. Hibernate Core  3.2.6 GA  -  3.2.x, 3.3.x  3.2.x, 3.3.x  3.0.x  3.0.x  3.0.x  3.2.x
  3. 3.3.2 GA  -  3.4.x  3.4.x  3.1.x  3.1.x  Not compatible  Not compatible

Hibernate 3.3.6 -->Annotation 3.2.X,3.3.X(兼容)

Hibernate 3.3.2-->Annotation 3.4.X(兼容)

2.slf4j 下载 http://www.slf4j.org/ 下载slf4j_x.jar

因为hibernate 中的日志使用的slf,所以必须下载

注意(slf4j_api_x.jar 必须与 slf4j_aop_x.jar 版本对应)。

3.导入jar包

view plain copy to clipboard print ?
  1. <classpathentry kind="lib" path="E:/java/Hibernate/hibernate-distribution-3.3.2.GA-dist/hibernate-distribution-3.3.2.GA/hibernate3.jar"/>
  2. <classpathentry kind="lib" path="E:/java/Hibernate/hibernate-distribution-3.3.2.GA-dist/hibernate-distribution-3.3.2.GA/lib/required/antlr-2.7.6.jar"/>
  3. <classpathentry kind="lib" path="E:/java/Hibernate/hibernate-distribution-3.3.2.GA-dist/hibernate-distribution-3.3.2.GA/lib/required/commons-collections-3.1.jar"/>
  4. <classpathentry kind="lib" path="E:/java/Hibernate/hibernate-distribution-3.3.2.GA-dist/hibernate-distribution-3.3.2.GA/lib/required/javassist-3.9.0.GA.jar"/>
  5. <classpathentry kind="lib" path="E:/java/Hibernate/hibernate-distribution-3.3.2.GA-dist/hibernate-distribution-3.3.2.GA/lib/required/jta-1.1.jar"/>
  6. <classpathentry kind="lib" path="E:/java/Hibernate/hibernate-distribution-3.3.2.GA-dist/hibernate-distribution-3.3.2.GA/lib/required/slf4j-api-1.5.8.jar"/>
  7. <classpathentry kind="lib" path="E:/java/Hibernate/hibernate-annotations-3.4.0.GA/hibernate-annotations-3.4.0.GA/hibernate-annotations.jar"/>
  8. <classpathentry kind="lib" path="E:/java/Hibernate/hibernate-annotations-3.4.0.GA/hibernate-annotations-3.4.0.GA/lib/dom4j.jar"/>
  9. <classpathentry kind="lib" path="E:/java/Hibernate/hibernate-annotations-3.4.0.GA/hibernate-annotations-3.4.0.GA/lib/ejb3-persistence.jar"/>
  10. <classpathentry kind="lib" path="E:/java/Hibernate/hibernate-annotations-3.4.0.GA/hibernate-annotations-3.4.0.GA/lib/hibernate-commons-annotations.jar"/>
  11. <classpathentry kind="lib" path="E:/java/sql连接/mysql-connector-java-5.1.11-bin.jar"/>
  12. <classpathentry kind="lib" path="E:/java/Hibernate/slf4j-1.5.8/slf4j-1.5.8/slf4j-nop-1.5.8.jar"/>

写hibernate.cfg.xml

查hibernate 文档可以知道格式

view plain copy to clipboard print ?
  1. <?xml version='1.0' encoding='utf-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7. <!-- Database connection settings -->
  8. <property name="connection.driver_class">org.hsqldb.jdbcDriver</property><!--数据库驱动-->
  9. <property name="connection.url">jdbc:hsqldb:hsql://localhost</property><!--数据库链接-->
  10. <property name="connection.username">sa</property><!--数据库用户名--!>
  11. <property name="connection.password"></property><!--密码--!>
  12. <!-- JDBC connection pool (use the built-in) -->
  13. <property name="connection.pool_size">1</property><!---->
  14. <!-- SQL dialect -->
  15. <property name="dialect">org.hibernate.dialect.HSQLDialect</property><!--数据库方言-->
  16. <!-- Enable Hibernate's automatic session context management -->
  17. <property name="current_session_context_class">thread</property>
  18. <!-- Disable the second-level cache  -->
  19. <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
  20. <!-- Echo all executed SQL to stdout -->
  21. <property name="show_sql">true</property>
  22. <!-- Drop and re-create the database schema on startup -->
  23. <property name="hbm2ddl.auto">create</property><!--生成建表语句,这里提供给我们4个值,查文档,试情况可以不写-->
  24. </session-factory>
  25. </hibernate-configuration>

4.写实体类 Teacher,

这里我们看不同主键(ID生成策略的代码)

1,Teacher类,ID为主键

view plain copy to clipboard print ?
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150

  1. package com.sccin.entity;
  2. import java.util.Date;
  3. import javax.persistence.Entity;
  4. import javax.persistence.Id;
  5. import javax.persistence.Temporal;
  6. import javax.persistence.TemporalType;
  7. import javax.persistence.Transient;
  8. @Entity
  9. public class Teacher {
  10. private int id;
  11. private String name;
  12. private int age;
  13. private String title;
  14. private Date birthday;
  15. private String youwifeName;
  16. @Transient
  17. public String getYouwifeName() {
  18. return youwifeName;
  19. }
  20. public void setYouwifeName(String youwifeName) {
  21. this.youwifeName = youwifeName;
  22. }
  23. @Temporal(TemporalType.DATE)
  24. public Date getBirthday() {
  25. return birthday;
  26. }
  27. public void setBirthday(Date birthday) {
  28. this.birthday = birthday;
  29. }
  30. @Id
  31. public int getId() {
  32. return id;
  33. }
  34. public void setId(int id) {
  35. this.id = id;
  36. }
  37. public String getName() {
  38. return name;
  39. }
  40. public void setName(String name) {
  41. this.name = name;
  42. }
  43. public int getAge() {
  44. return age;
  45. }
  46. public void setAge(int age) {
  47. this.age = age;
  48. }
  49. public String getTitle() {
  50. return title;
  51. }
  52. public void setTitle(String title) {
  53. this.title = title;
  54. }
  55. }

注:在这个类里上写@Entity 我们要让ID为主键,只需要在getId()方法上写上@Id 就行了。

@Transient 表示该属性不与数据库表映射

@Temporal(TemporalType.DATE) 表示设置类型精度,这个字段为DATE类型,映射到数据库表中类型为Date,只有日期,没有时间精度

写好了实体类,需要把这个映射添加到hibernate.cfg.xml中

view plain copy to clipboard print ?
  1. <mapping class="com.sccin.entity.Teacher"/>

写个方法测试:

view plain copy to clipboard print ?
  1. //保存一个ID=1的Teacher的实体
  2. public void teachersave() {
  3. Teacher t = new Teacher();
  4. t.setId(1);
  5. t.setName("yang");
  6. t.setBirthday(new Date());
  7. t.setTitle("T1");
  8. t.setAge(20);
  9. Session session = sessionfactory.openSession();
  10. session.beginTransaction();
  11. session.save(t);
  12. session.getTransaction().commit();
  13. session.close();
  14. }

这里主键没有写生成策略,需要我们手动给主键设置值,很容易发生冲突。

我们一般把主键安装需求设置成它自动增长,有不同的策略。

  看官方文档给我们的ID生成策略有哪些

+ expand source view plain copy to clipboard print ?

当然这些很多不常用。

这里不做解释,看Annotation中怎么标识主键

需要在主键上增加一个@Id标识

view plain copy to clipboard print ?
  1. @Id
  2. @GeneratedValue(strategy = GenerationType.IDENTITY)
  3. public int getId() {
  4. return id;
  5. }

GenerationType 类型的枚举值,它的内容将指定 OpenJPA 容器自动生成实体标识的方式。有 GeneratorType.AUTO,GenerationType.IDENTITY,GenerationType.SEQUENCE, GenerationType.TABLE 四种方式

@GeneratedValue(strategy = GenerationType.IDENTITY)

一般可以根据你采取的底层数据库来选择,比如是用oracle,id用sequence的话,可以采取sequence方式,如果是用mysql,一般就用auto模式

// 默认相当于native ID生成策略,JPA 1.0 中只有4个可选值 
         // 如果只写@Id ,主键字段不会自动产生,需要我们手动输入 
         // @GeneratedValue 默认为策略产生ID 
         // 如果我要让ID为IDENTITY 则需要手动给他指定值--@GeneratedValue(strategy=GenerationType.IDENTITY)

这样选择了主键生成策略,在给实体赋值时就不用设置ID值了。

GenerationType.SEQUENCE 在Oracle中选择这种策略会在数据库中自动建一个为名“Hibernate_Sequence”的SEQUENCE,如果要改这个名字需要另外设置,也很简单,查文档

GenerationType.TABLE  这中方式是 建一个数据库表 来管理ID主键····省略。

除了这种方式,有些需求要让多个字段合为主键:联合主键

联合主键 
     1.建主键类:Teacher_PK(作为主键)

view plain copy to clipboard print ?
  1. package com.sccin.entity;
  2. import java.io.Serializable;
  3. public class Teacher_PK implements Serializable {
  4. private int id;
  5. private String name;
  6. public int getId() {
  7. return id;
  8. }
  9. public void setId(int id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. @Override
  19. public boolean equals(Object o) {
  20. if (o instanceof Teacher_PK) {
  21. Teacher_PK pk = (Teacher_PK) o;
  22. if (this.id == pk.getId() && this.name.equals(pk.getName())) {
  23. return true;
  24. }
  25. }
  26. return false;
  27. }
  28. @Override
  29. public int hashCode() {
  30. return this.hashCode();
  31. }
  32. }

2.修改Teacher 类

view plain copy to clipboard print ?
  1. package com.sccin.entity;
  2. import java.util.Date;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.GenerationType;
  6. import javax.persistence.Id;
  7. import javax.persistence.IdClass;
  8. import javax.persistence.Temporal;
  9. import javax.persistence.TemporalType;
  10. import javax.persistence.Transient;
  11. @Entity
  12. @IdClass(Teacher_PK.class)
  13. public class Teacher {
  14. private int id;
  15. private String name;
  16. private int age;
  17. private String title;
  18. private Date birthday;
  19. private String youwifeName;
  20. @Transient
  21. public String getYouwifeName() {
  22. return youwifeName;
  23. }
  24. public void setYouwifeName(String youwifeName) {
  25. this.youwifeName = youwifeName;
  26. }
  27. @Temporal(TemporalType.DATE)
  28. public Date getBirthday() {
  29. return birthday;
  30. }
  31. public void setBirthday(Date birthday) {
  32. this.birthday = birthday;
  33. }
  34. @Id
  35. public int getId() {
  36. return id;
  37. }
  38. public void setId(int id) {
  39. this.id = id;
  40. }
  41. @Id
  42. public String getName() {
  43. return name;
  44. }
  45. public void setName(String name) {
  46. this.name = name;
  47. }
  48. public int getAge() {
  49. return age;
  50. }
  51. public void setAge(int age) {
  52. this.age = age;
  53. }
  54. public String getTitle() {
  55. return title;
  56. }
  57. public void setTitle(String title) {
  58. this.title = title;
  59. }
  60. }

这样ID,与Name就作为一个联合的主键

联合主键在Annotation中只需要在类上标识@IdClass(Teacher_PK.class)指定哪个类是联合主键类,

Hibernate Annotation相关推荐

  1. Hibernate Annotation 学习

    1.一对多关联,级联操作 @OneToMany(mappedBy = "paymentad", cascade = CascadeType.ALL, fetch = FetchTy ...

  2. hibernate annotation注解方式来处理映射关系

    2019独角兽企业重金招聘Python工程师标准>>> 在hibernate中,通常配置对象关系映射关系有两种,一种是基于xml的方式,另一种是基于annotation的注解方式,熟 ...

  3. Hibernate Annotation的 *ToOne默认的FetchType是EAGER的

    Hibernate Annotation的 *ToOne默认的FetchType是EAGER的 public class Entry{ ... @ManyToOne(targetEntity = Us ...

  4. hibernate annotation多对多中间表添加其他字段的第三种方法

    本示例主要以学生(T_Student)和课程(T_Course)之间的多对多关系,中间表Score(分数),学生表和课程表是多对多关系,另外为他们的关系添加额外的字段---分数: T_Student类 ...

  5. Hibernate.Annotation注解

    Hibernate注解 1.@Entity(name="EntityName") 必须,name为可选,对应数据库中一的个表 2.@Table(name="", ...

  6. Hibernate Annotation中英文文档链接下载 (Hibernate 注解)

    官网进入:http://www.hibernate.org 说明文档: 英文:http://docs.jboss.org/hibernate/annotations/3.5/reference/en/ ...

  7. Hibernate Annotation _List/Map

    // Student.java 实体类package com.tao.pojo;import java.util.List;public class Student {private int id;p ...

  8. Hibernate annotation多对多配置

    角色(用户组),用户多对多. 角色实体配置: private Set<TAuthUser> users;@ManyToMany@JoinTable(name="t_auth_us ...

  9. hibernate annotation注解 columnDefinition用法

    column注解中的columnDefinition属性用于覆盖数据库DDL中的语句:(MySql) @Column(columnDefinition = "int(11) DEFAULT ...

最新文章

  1. android HTTP发送及MD5加密收集
  2. 【微信开发】微信开发 之 开启开发模式
  3. 为Feign设置Header信息
  4. 今年最火的 Golang 云原生开源项目,可能就是它了!
  5. Winform中使用NPOI实现Excel导入并赋值给DataTable
  6. github大学课程_GitHub基础教程:如何使用GitHub课程
  7. java暂停另一个线程_如何从另一个线程终止或暂停Rust线程?
  8. 一款非常好看的雷姆背景的时间单页(附雷姆图片)
  9. 在CentOS下为sqlplus和rman 添加rlwrap
  10. 浅谈 js 数字格式类型
  11. 简评游戏人工智能相关的中文书(补遗)
  12. 51Nod 1637 幸运数字转换(思维)
  13. Struts2面试题分析
  14. PDF解密去水印工具
  15. 计算机应用技术专业的周志,计算机科学与技术专业实习周记
  16. python项目报告怎么写_python项目
  17. c语言判断闰年次数,C语言判断闰年,即判断年份是否为闰年
  18. 中国MES市场主流厂商及产品分析
  19. mysql怎么改gm_MySQL修改密码的几种方式
  20. mac屏幕保护SaveHollywood安装方法

热门文章

  1. Python中yield的简单理解
  2. 安装rouge和pyrouge
  3. ScriptManager.RegisterStartupScript()方法
  4. 非递归实现二叉树的遍历
  5. linux让前台程序脱离终端运行
  6. 微信小程序配置服务器域名和业务域名
  7. Mybatis之xml方式(一)
  8. AMR SLAM ROS入门——前言
  9. 【魏先生搞定Python系列】一文搞定Cufflinks画图
  10. unittest篇3-测试套件(TestSuite)详解