一.JPA简介--Java Persistence API。

是SUN公司推出的一套基于ORM的规范。hibernate框架中提供了JPA的实现。JPA通过JDK5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

优势:标准化/容器级特性的支持/简单方便/JPQL查询/面向对象的高级特性

二.基于JPA注解的单表映射

a.导入Hibernate必备的13个jar包;

b.创建Hibernate核心配置文件:hibernate.cfg.xml
   

  1. 1 <?xml version="1.0" encoding="UTF-8"?>
  2. 2 <!DOCTYPE hibernate-configuration PUBLIC
  3. 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5. 5 <hibernate-configuration>
  6. 6 <session-factory>
  7. 7 <!--数据库配置 -->
  8. 8 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  9. 9 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  10. 10 <property name="hibernate.connection.url">jdbc:mysql:///day58</property>
  11. 11 <property name="hibernate.connection.username">root</property>
  12. 12 <property name="hibernate.connection.password">root</property>
  13. 13 <!--hibernate基本配置 -->
  14. 14 <property name="hibernate.hbm2ddl.auto">create</property>
  15. 15 <property name="hibernate.show_sql">true</property>
  16. 16 <property name="hibernate.format_sql">true</property>
  17. 17 <!--配置数据源的提供商 (记得导入c3p0jar包) -->
  18. 18 <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
  19. 19 <!--配置事务的隔离级别 -->
  20. 20 <property name="hibernate.connection.isolation">4</property>
  21. 21 <!--配置与当前线程绑定的session对象 -->
  22. 22 <property name="hibernate.current_session_context_class">thread</property>
  23. 23 <!--指定映射文件位置 (文件变为class,属性值为类的全限定名) -->
  24. 24 <mapping class="huguangqin.com.cnblogs.entity.Customer"/>
  25. 25 </session-factory>
  26. 26 </hibernate-configuration>

c.使用JPA注解配置实体类
   

  1. 1 package huguangqin.com.cnblogs.entity;
  2. 2 import java.io.Serializable;
  3. 3 import javax.persistence.Column;
  4. 4 import javax.persistence.Entity;
  5. 5 import javax.persistence.GeneratedValue;
  6. 6 import javax.persistence.GenerationType;
  7. 7 import javax.persistence.Id;
  8. 8 import javax.persistence.Table;
  9. 9
  10. 10 @Entity // 表示当前类是一个实体类
  11. 11 @Table(name = "cst_customer") // 建立当前实体类与表之间的对应关系
  12. 12 public class Customer implements Serializable {
  13. 13 @Id // 表示当前属性为主键
  14. 14 @GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主键生成策略
  15. 15 @Column(name = "cust_id") // 属性对应的字段名
  16. 16 private Long custId;
  17. 17 @Column(name = "cust_name")
  18. 18 private String custName;
  19. 19 @Column(name = "cust_source")
  20. 20 private String custSource;
  21. 21 @Column(name = "cust_industry")
  22. 22 private String custIndustry;
  23. 23 @Column(name = "cust_level")
  24. 24 private String custLevel;
  25. 25 @Column(name = "cust_address")
  26. 26 private String custAddress;
  27. 27 @Column(name = "cust_phone")
  28. 28 private String custPhone;
  29. 29
  30. 30 public Long getCustId() {
  31. 31 return custId;
  32. 32 }
  33. 33
  34. 34 public void setCustId(Long custId) {
  35. 35 this.custId = custId;
  36. 36 }
  37. 37
  38. 38 public String getCustName() {
  39. 39 return custName;
  40. 40 }
  41. 41
  42. 42 public void setCustName(String custName) {
  43. 43 this.custName = custName;
  44. 44 }
  45. 45
  46. 46 public String getCustSource() {
  47. 47 return custSource;
  48. 48 }
  49. 49
  50. 50 public void setCustSource(String custSource) {
  51. 51 this.custSource = custSource;
  52. 52 }
  53. 53
  54. 54 public String getCustIndustry() {
  55. 55 return custIndustry;
  56. 56 }
  57. 57
  58. 58 public void setCustIndustry(String custIndustry) {
  59. 59 this.custIndustry = custIndustry;
  60. 60 }
  61. 61
  62. 62 public String getCustLevel() {
  63. 63 return custLevel;
  64. 64 }
  65. 65
  66. 66 public void setCustLevel(String custLevel) {
  67. 67 this.custLevel = custLevel;
  68. 68 }
  69. 69
  70. 70 public String getCustAddress() {
  71. 71 return custAddress;
  72. 72 }
  73. 73
  74. 74 public void setCustAddress(String custAddress) {
  75. 75 this.custAddress = custAddress;
  76. 76 }
  77. 77
  78. 78 public String getCustPhone() {
  79. 79 return custPhone;
  80. 80 }
  81. 81
  82. 82 public void setCustPhone(String custPhone) {
  83. 83 this.custPhone = custPhone;
  84. 84 }
  85. 85
  86. 86 // toString
  87. 87 @Override
  88. 88 public String toString() {
  89. 89 return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource
  90. 90 + ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress
  91. 91 + ", custPhone=" + custPhone + "]";
  92. 92 }
  93. 93
  94. 94 }
  95. 95

d.实现保存功能
   

  1. 1 package huguangqin.com.cnblogs.demo;
  2. 2 import org.hibernate.Session;
  3. 3 import org.hibernate.Transaction;
  4. 4 import org.junit.Test;
  5. 5 import huguangqin.com.cnblogs.entity.Customer;
  6. 6 import huguangqin.com.cnblogs.util.HibernateUtils;
  7. 7
  8. 8 /**
  9. 9 * 实现保存一个客户的功能
  10. 10 */
  11. 11 public class JPATest {
  12. 12 @Test
  13. 13 public void add() {
  14. 14 // 获取session
  15. 15 Session cs = HibernateUtils.getCurrentSession();
  16. 16 // 开启事务
  17. 17 Transaction tx = cs.beginTransaction();
  18. 18 // 创建对象
  19. 19 Customer c = new Customer();
  20. 20 c.setCustName("大通股份");
  21. 21 // 保存
  22. 22 cs.save(c);
  23. 23 // 提交
  24. 24 tx.commit();
  25. 25 }
  26. 26 }
  27. 27

常用注解说明:
     @Entity
         作用:指定当前类是实体类。写上此注解用于在创建SessionFactory时,加载映射配置。
     @Table
         作用:指定实体类和表之间的对应关系。
         属性:
             name:指定数据库表的名称
     @Id
         作用:指定当前字段是主键。
     @GeneratedValue
         作用:指定主键的生成方式。
         属性:
             strategy :指定主键生成策略。JPA支持四种生成策略:TABLE,SEQUENCE,IDENTITY,AUTO。
                 IDENTITY:主键由数据库自动生成(主要是自动增长型);mysql
                 SEQUENCE:根据底层数据库的序列来生成主键,条件是数据库支持序列。 oracle
                 AUTO:主键由程序控制。
                 TABLE:使用一个特定的数据库表格来保存主键。

@Column
         作用:指定实体类属性和数据库表之间的对应关系
         属性:
             name:指定数据库表的列名称。
             unique:是否唯一 
             nullable:是否可以为空 
             inserttable:是否可以插入 
             updateable:是否可以更新 
             columnDefinition: 定义建表时创建此列的DDL 
             secondaryTable: 从表名。如果此列不建在主表上(默认建在主表),该属性定义该列所在从表的名字。

三.一对多关系映射

注解说明:
     @OneToMany:
         作用:建立一对多的关系映射
         属性:
             targetEntityClass:指定多方的类的字节码
             mappedBy:指定从表实体类中引用主表对象的名称。
             cascade:指定要使用的级联操作
             fetch:指定是否采用延迟加载
             orphanRemoval:是否使用孤儿删除
     @ManyToOne
         作用:建立多对一的关系
         属性:
              targetEntityClass:指定一的一方实体类字节码
             cascade:指定要使用的级联操作
             fetch:指定是否采用延迟加载
             optional:关联是否可选。如果设置为false,则必须始终存在非空关系。
     @JoinColumn
         作用:用于定义主键字段和外键字段的对应关系。
         属性:
             name:指定外键字段的名称
             referencedColumnName:指定引用主表的主键字段名称
             unique:是否唯一。默认值不唯一
             nullable:是否允许为空。默认值允许。
             insertable:是否允许插入。默认值允许。
             updatable:是否允许更新。默认值允许。
             columnDefinition:列的定义信息。

示例:双向一对多关系

实体类-Customer:
   

  1. 1 package huguangqin.com.cnblogs.entity;
  2. 2 import java.io.Serializable;
  3. 3 import java.util.HashSet;
  4. 4 import java.util.Set;
  5. 5 import javax.persistence.CascadeType;
  6. 6 import javax.persistence.Column;
  7. 7 import javax.persistence.Entity;
  8. 8 import javax.persistence.GeneratedValue;
  9. 9 import javax.persistence.GenerationType;
  10. 10 import javax.persistence.Id;
  11. 11 import javax.persistence.OneToMany;
  12. 12 import javax.persistence.Table;
  13. 13
  14. 14 @Entity // 表示当前类是一个实体类
  15. 15 @Table(name = "cst_customer") // 建立当前实体类与表之间的对应关系
  16. 16 public class Customer implements Serializable {
  17. 17 @Id // 表示当前属性为主键
  18. 18 @GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主键生成策略
  19. 19 @Column(name = "cust_id") // 属性对应的字段名
  20. 20 private Long custId;
  21. 21 @Column(name = "cust_name")
  22. 22 private String custName;
  23. 23 @Column(name = "cust_source")
  24. 24 private String custSource;
  25. 25 @Column(name = "cust_industry")
  26. 26 private String custIndustry;
  27. 27 @Column(name = "cust_level")
  28. 28 private String custLevel;
  29. 29 @Column(name = "cust_address")
  30. 30 private String custAddress;
  31. 31 @Column(name = "cust_phone")
  32. 32 private String custPhone;
  33. 33 // 一对多,此处为关键处,mappedBy-放弃外键维护权
  34. 34 @OneToMany(targetEntity = Linkman.class, mappedBy = "customer", cascade = CascadeType.ALL)
  35. 35 private Set<Linkman> linkmans = new HashSet<>();
  36. 36
  37. 37 public Set<Linkman> getLinkmans() {
  38. 38 return linkmans;
  39. 39 }
  40. 40
  41. 41 public void setLinkmans(Set<Linkman> linkmans) {
  42. 42 this.linkmans = linkmans;
  43. 43 }
  44. 44
  45. 45 public Long getCustId() {
  46. 46 return custId;
  47. 47 }
  48. 48
  49. 49 public void setCustId(Long custId) {
  50. 50 this.custId = custId;
  51. 51 }
  52. 52
  53. 53 public String getCustName() {
  54. 54 return custName;
  55. 55 }
  56. 56
  57. 57 public void setCustName(String custName) {
  58. 58 this.custName = custName;
  59. 59 }
  60. 60
  61. 61 public String getCustSource() {
  62. 62 return custSource;
  63. 63 }
  64. 64
  65. 65 public void setCustSource(String custSource) {
  66. 66 this.custSource = custSource;
  67. 67 }
  68. 68
  69. 69 public String getCustIndustry() {
  70. 70 return custIndustry;
  71. 71 }
  72. 72
  73. 73 public void setCustIndustry(String custIndustry) {
  74. 74 this.custIndustry = custIndustry;
  75. 75 }
  76. 76
  77. 77 public String getCustLevel() {
  78. 78 return custLevel;
  79. 79 }
  80. 80
  81. 81 public void setCustLevel(String custLevel) {
  82. 82 this.custLevel = custLevel;
  83. 83 }
  84. 84
  85. 85 public String getCustAddress() {
  86. 86 return custAddress;
  87. 87 }
  88. 88
  89. 89 public void setCustAddress(String custAddress) {
  90. 90 this.custAddress = custAddress;
  91. 91 }
  92. 92
  93. 93 public String getCustPhone() {
  94. 94 return custPhone;
  95. 95 }
  96. 96
  97. 97 public void setCustPhone(String custPhone) {
  98. 98 this.custPhone = custPhone;
  99. 99 }
  100. 100
  101. 101 // toString
  102. 102 @Override
  103. 103 public String toString() {
  104. 104 return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource
  105. 105 + ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress
  106. 106 + ", custPhone=" + custPhone + "]";
  107. 107 }
  108. 108
  109. 109 }
  110. 110

实体类-Linkman
    

  1. 1 package huguangqin.com.cnblogs.entity;
  2. 2 import java.io.Serializable;
  3. 3 import javax.persistence.Column;
  4. 4 import javax.persistence.Entity;
  5. 5 import javax.persistence.GeneratedValue;
  6. 6 import javax.persistence.GenerationType;
  7. 7 import javax.persistence.Id;
  8. 8 import javax.persistence.JoinColumn;
  9. 9 import javax.persistence.ManyToOne;
  10. 10 import javax.persistence.Table;
  11. 11
  12. 12 @Entity
  13. 13 @Table(name = "cst_linkman")
  14. 14 public class Linkman implements Serializable {
  15. 15 @Id
  16. 16 @GeneratedValue(strategy = GenerationType.IDENTITY)
  17. 17 @Column(name = "lkm_id")
  18. 18 private Long lkmId;// 联系人编号(主键)
  19. 19 @Column(name = "lkm_name")
  20. 20 private String lkmName;// 姓名
  21. 21 @Column(name = "lkm_gender")
  22. 22 private String lkmGender;// 性别
  23. 23 @Column(name = "lkm_phone")
  24. 24 private String lkmPhone;// 办 公电话
  25. 25 @Column(name = "lkm_mobile")
  26. 26 private String lkmMobile;// 手机
  27. 27 @Column(name = "lkm_email")
  28. 28 private String lkmEmail;// 邮箱
  29. 29 @Column(name = "lkm_position")
  30. 30 private String lkmPosition;// 职位
  31. 31 @Column(name = "lkm_memo")
  32. 32 private String lkmMemo;// 备注
  33. 33 // 多个linkman对应一个customer,此处为关键
  34. 34 @ManyToOne(targetEntity = Customer.class)
  35. 35 @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id") // 指定外键名和参照主键
  36. 36 private Customer customer;
  37. 37
  38. 38 public Customer getCustomer() {
  39. 39 return customer;
  40. 40 }
  41. 41
  42. 42 public void setCustomer(Customer customer) {
  43. 43 this.customer = customer;
  44. 44 }
  45. 45
  46. 46 // getter/setter
  47. 47 public Long getLkmId() {
  48. 48 return lkmId;
  49. 49 }
  50. 50
  51. 51 public void setLkmId(Long lkmId) {
  52. 52 this.lkmId = lkmId;
  53. 53 }
  54. 54
  55. 55 public String getLkmName() {
  56. 56 return lkmName;
  57. 57 }
  58. 58
  59. 59 public void setLkmName(String lkmName) {
  60. 60 this.lkmName = lkmName;
  61. 61 }
  62. 62
  63. 63 public String getLkmGender() {
  64. 64 return lkmGender;
  65. 65 }
  66. 66
  67. 67 public void setLkmGender(String lkmGender) {
  68. 68 this.lkmGender = lkmGender;
  69. 69 }
  70. 70
  71. 71 public String getLkmPhone() {
  72. 72 return lkmPhone;
  73. 73 }
  74. 74
  75. 75 public void setLkmPhone(String lkmPhone) {
  76. 76 this.lkmPhone = lkmPhone;
  77. 77 }
  78. 78
  79. 79 public String getLkmMobile() {
  80. 80 return lkmMobile;
  81. 81 }
  82. 82
  83. 83 public void setLkmMobile(String lkmMobile) {
  84. 84 this.lkmMobile = lkmMobile;
  85. 85 }
  86. 86
  87. 87 public String getLkmEmail() {
  88. 88 return lkmEmail;
  89. 89 }
  90. 90
  91. 91 public void setLkmEmail(String lkmEmail) {
  92. 92 this.lkmEmail = lkmEmail;
  93. 93 }
  94. 94
  95. 95 public String getLkmPosition() {
  96. 96 return lkmPosition;
  97. 97 }
  98. 98
  99. 99 public void setLkmPosition(String lkmPosition) {
  100. 100 this.lkmPosition = lkmPosition;
  101. 101 }
  102. 102
  103. 103 public String getLkmMemo() {
  104. 104 return lkmMemo;
  105. 105 }
  106. 106
  107. 107 public void setLkmMemo(String lkmMemo) {
  108. 108 this.lkmMemo = lkmMemo;
  109. 109 }
  110. 110
  111. 111 // toString
  112. 112 @Override
  113. 113 public String toString() {
  114. 114 return "Linkman [lkmId=" + lkmId + ", lkmName=" + lkmName + ", lkmGender=" + lkmGender + ", lkmPhone="
  115. 115 + lkmPhone + ", lkmMobile=" + lkmMobile + ", lkmEmail=" + lkmEmail + ", lkmPosition=" + lkmPosition
  116. 116 + ", lkmMemo=" + lkmMemo + "]";
  117. 117 }
  118. 118
  119. 119 }
  120. 120

测试代码:
    

  1. 1 package huguangqin.com.cnblogs.demo;
  2. 2
  3. 3 import org.hibernate.Session;
  4. 4 import org.hibernate.Transaction;
  5. 5 import org.junit.Test;
  6. 6
  7. 7 import huguangqin.com.cnblogs.entity.Customer;
  8. 8 import huguangqin.com.cnblogs.entity.Linkman;
  9. 9 import huguangqin.com.cnblogs.util.HibernateUtils;
  10. 10
  11. 11 /**
  12. 12 * 一对多,保存一个客户,即能保存对应的多个联系人
  13. 13 */
  14. 14 public class JPATest01 {
  15. 15 @Test
  16. 16 public void add() {
  17. 17 // 获取session
  18. 18 Session cs = HibernateUtils.getCurrentSession();
  19. 19 // 开启事务,并返回事务对象
  20. 20 Transaction tx = cs.beginTransaction();
  21. 21 // 创建对象
  22. 22 Customer c = new Customer();
  23. 23 c.setCustName("百度");
  24. 24 Linkman man = new Linkman();
  25. 25 man.setLkmName("大王");
  26. 26 // 创建关系--双方均需创建关系,否则外键添加不上
  27. 27 c.getLinkmans().add(man);
  28. 28 man.setCustomer(c);
  29. 29 // 保存
  30. 30 cs.save(c);
  31. 31 // 提交事务
  32. 32 tx.commit();
  33. 33 }
  34. 34 }
  35. 35

四.多对多关系映射

注解说明
     @ManyToMany
         作用:用于映射多对多关系
         属性:
             cascade:配置级联操作。
             fetch:配置是否采用延迟加载。
             targetEntity:配置目标的实体类。映射多对多的时候不用写。
     @JoinTable
         作用:针对中间表的配置
         属性:
             nam:配置中间表的名称
             joinColumns:中间表的外键字段关联当前实体类所对应表的主键字段
             inverseJoinColumn:中间表的外键字段关联对方表的主键字段
     @JoinColumn
         作用:用于定义主键字段和外键字段的对应关系。
         属性:
             name:指定外键字段的名称
             referencedColumnName:指定引用主表的主键字段名称
             unique:是否唯一。默认值不唯一
             nullable:是否允许为空。默认值允许。
             insertable:是否允许插入。默认值允许。
             updatable:是否允许更新。默认值允许。
             columnDefinition:列的定义信息。

示例:多对多关系

实体类:-User
   

  1. 1 package huguangqin.com.cnblogs.entity;
  2. 2 import java.io.Serializable;
  3. 3 import java.util.HashSet;
  4. 4 import java.util.Set;
  5. 5 import javax.persistence.CascadeType;
  6. 6 import javax.persistence.Column;
  7. 7 import javax.persistence.Entity;
  8. 8 import javax.persistence.GeneratedValue;
  9. 9 import javax.persistence.GenerationType;
  10. 10 import javax.persistence.Id;
  11. 11 import javax.persistence.JoinColumn;
  12. 12 import javax.persistence.JoinTable;
  13. 13 import javax.persistence.ManyToMany;
  14. 14 import javax.persistence.Table;
  15. 15
  16. 16 @Entity
  17. 17 @Table(name = "user")
  18. 18 public class User implements Serializable {
  19. 19
  20. 20 @Id
  21. 21 @GeneratedValue(strategy = GenerationType.IDENTITY)
  22. 22 @Column(name = "user_id")
  23. 23 private Long userId;
  24. 24
  25. 25 @Column(name = "user_name")
  26. 26 private String userName;
  27. 27
  28. 28 @Column
  29. 29 private String address;
  30. 30
  31. 31 // 对应多个角色
  32. 32 @ManyToMany(targetEntity = Role.class, cascade = CascadeType.ALL)
  33. 33 @JoinTable(name = "role_user",
  34. 34 joinColumns = {@JoinColumn(name = "sys_user_id", referencedColumnName = "user_id") },
  35. 35 inverseJoinColumns = {@JoinColumn(name = "sys_role_id", referencedColumnName = "role_id") })
  36. 36 private Set<Role> roles = new HashSet<>(0);
  37. 37
  38. 38 // getter/setter
  39. 39 public Long getUserId() {
  40. 40 return userId;
  41. 41 }
  42. 42
  43. 43 public void setUserId(Long userId) {
  44. 44 this.userId = userId;
  45. 45 }
  46. 46
  47. 47 public String getUserName() {
  48. 48 return userName;
  49. 49 }
  50. 50
  51. 51 public void setUserName(String userName) {
  52. 52 this.userName = userName;
  53. 53 }
  54. 54
  55. 55 public String getAddress() {
  56. 56 return address;
  57. 57 }
  58. 58
  59. 59 public void setAddress(String address) {
  60. 60 this.address = address;
  61. 61 }
  62. 62
  63. 63 public Set<Role> getRoles() {
  64. 64 return roles;
  65. 65 }
  66. 66
  67. 67 public void setRoles(Set<Role> roles) {
  68. 68 this.roles = roles;
  69. 69 }
  70. 70
  71. 71 // toString
  72. 72 @Override
  73. 73 public String toString() {
  74. 74 return "User [userId=" + userId + ", userName=" + userName + ", address=" + address + ", roles=" + roles + "]";
  75. 75 }
  76. 76
  77. 77 }
  78. 78

实体类:Role
    

  1. 1 package huguangqin.com.cnblogs.entity;
  2. 2 import java.io.Serializable;
  3. 3 import java.util.HashSet;
  4. 4 import java.util.Set;
  5. 5 import javax.persistence.Column;
  6. 6 import javax.persistence.Entity;
  7. 7 import javax.persistence.GeneratedValue;
  8. 8 import javax.persistence.GenerationType;
  9. 9 import javax.persistence.Id;
  10. 10 import javax.persistence.ManyToMany;
  11. 11 import javax.persistence.Table;
  12. 12
  13. 13 @Entity
  14. 14 @Table(name = "role")
  15. 15 public class Role implements Serializable {
  16. 16
  17. 17 @Id
  18. 18 @GeneratedValue(strategy = GenerationType.IDENTITY)
  19. 19 @Column(name = "role_id")
  20. 20 private Long roleId;
  21. 21
  22. 22 @Column(name = "role_name")
  23. 23 private String roleName;
  24. 24
  25. 25 // 对应多个用户
  26. 26 @ManyToMany(mappedBy = "roles") // 放弃维护权,已由对方Role属性维护
  27. 27 private Set<User> users = new HashSet<>(0);
  28. 28
  29. 29 // getter/setter
  30. 30 public Long getRoleId() {
  31. 31 return roleId;
  32. 32 }
  33. 33
  34. 34 public void setRoleId(Long roleId) {
  35. 35 this.roleId = roleId;
  36. 36 }
  37. 37
  38. 38 public String getRoleName() {
  39. 39 return roleName;
  40. 40 }
  41. 41
  42. 42 public void setRoleName(String roleName) {
  43. 43 this.roleName = roleName;
  44. 44 }
  45. 45
  46. 46 public Set<User> getUsers() {
  47. 47 return users;
  48. 48 }
  49. 49
  50. 50 public void setUsers(Set<User> users) {
  51. 51 this.users = users;
  52. 52 }
  53. 53
  54. 54 // toString
  55. 55 @Override
  56. 56 public String toString() {
  57. 57 return "Role [roleId=" + roleId + ", roleName=" + roleName + ", users=" + users + "]";
  58. 58 }
  59. 59
  60. 60 }
  61. 61
  62. 62 测试代码:
  63. 63 package huguangqin.com.cnblogs.demo;
  64. 64 import org.hibernate.Session;
  65. 65 import org.hibernate.Transaction;
  66. 66 import org.junit.Test;
  67. 67 import huguangqin.com.cnblogs.entity.Role;
  68. 68 import huguangqin.com.cnblogs.entity.User;
  69. 69 import huguangqin.com.cnblogs.util.HibernateUtils;
  70. 70
  71. 71 public class AnotationTest {
  72. 72 @Test
  73. 73 public void test() {
  74. 74 // 获取Session
  75. 75 Session cs = HibernateUtils.getCurrentSession();
  76. 76 // 开启事务
  77. 77 Transaction tx = cs.beginTransaction();
  78. 78 // 构建对象
  79. 79 Role r = new Role();
  80. 80 r.setRoleName("model");
  81. 81 User u = new User();
  82. 82 u.setUserName("Rose");
  83. 83 // 创建关系
  84. 84 r.getUsers().add(u);
  85. 85 u.getRoles().add(r);
  86. 86 // 保存,由于设置了级联操作,只保存一个即可
  87. 87 cs.save(u);
  88. 88 // 提交事务
  89. 89 tx.commit();
  90. 90 }
  91. 91
  92. 92 }
  93. 93

Hibernate笔记6-JPA-注解的更多相关文章

  1. Java、Hibernate(JPA)注解大全

    1.@Entity(name=”EntityName”) 必须,name为可选,对应数据库中一的个表 2.@Table(name=””,catalog=””,schema=””) 可选,通常和@Ent ...

  2. Spring+Hibernate+struts2+JPA 注解+跨域//完成手机端点击加载更多 下拉加载更多

    一.使用IDEA新建一个maven项目(student) 1.1.0编写pom文件,添加项目所需要的包 <?xml version="1.0" encoding=" ...

  3. Hibernate 和 JPA 注解

    转载请注明:Hibernate 和 JPA 注解 | 言曌博客 1.@Entity(name="EntityName") 必须, name为可选,对应数据库中一的个表 2.@Tab ...

  4. hibernate笔记--使用注解(annotation)方式配置单(双)向多对一的映射关系

    前面几篇都是介绍的用配置文件来实现实体类到数据库表的映射,这种方式是比较麻烦的,每一个pojo类都需要写一个相应的*.hbm.xml,无疑增加了很多代码量,不过也有优点就是利于维护,为了方便开发,Hi ...

  5. JPA学习笔记1——JPA基础

    1.JPA简介: Java持久化规范,是从EJB2.x以前的实体Bean(Entity bean)分离出来的,EJB3以后不再有实体bean,而是将实体bean放到JPA中实现.JPA是sun提出的一 ...

  6. jpa 注解使用说明

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

  7. 再谈Hibernate级联删除——JPA下的Hibernate实现一对多级联删除CascadeType.DELETE_ORPHAN

    声明: 1.本文系原创,非抄袭或转载过来的. 2.本文论点都亲手做过实验论证. 3.本文所讲的Hibernate配置都基于注解的方式,hbm语法未提供. 非常多人对持久层概念搞不清JPA.Hibern ...

  8. springBoot注解大全JPA注解springMVC相关注解全局异常处理

    https://www.cnblogs.com/tanwei81/p/6814022.html 一.注解(annotations)列表 @SpringBootApplication:包含了@Compo ...

  9. JPA注解实现联合主键

    当表中一个主键不能唯一标识一条记录的时候,就需要使用联合主键了,下面是使用JPA注解实现联合主键的代码 1 首先需要建立一个复合主键类,用来存放需要生产联合主键的属性,该类需要实现序列化. packa ...

  10. Hibernate关系映射(注解)

    1.类级别注解 @Entity     映射实体类 @Table    映射数句库表 @Entity(name="tableName") - 必须,注解将一个类声明为一个实体bea ...

随机推荐

  1. 10、RNA-seq for DE analysis training(Mapping to assign reads to genes)

    1.Goal of mapping 1)We want to assign reads to genes they were derived from 2)The result of the mapp ...

  2. iOS开发,在main thread以外的thread更新UI

    如果需要在异步任务(Async Task)中更新UI,若直接设置UI,会导致程序崩溃. 例如,在异步block中去更改UI: NSOperationQueue *queue=[[NSOperation ...

  3. C# -- 继承规则

    例子1--C#继承的常见问题: using System; using System.Collections.Generic; using System.Linq; using System.Text ...

  4. JSONCPP学习笔记

    基本使用 使用jsoncpp库解析.修改.打印JSON串 源文件 $ cat main.cpp #include <iostream> #include "json/json.h ...

  5. BZOJ 3211【线段树】

    题意: n个数,m个操作. 1,L,R  询问[L , R] 的总和. 2,L,R  将区间所有数都开根号. 思路: 区间和简单. 主要就是一个 区间所有元素相同的标记Same ,但是这样是不是要求太 ...

  6. hdu 1847 Good Luck in CET-4 Everybody!(巴什博弈)

    Good Luck in CET-4 Everybody! HDU - 1847 大学英语四级考试就要来临了,你是不是在紧张的复习?也许紧张得连短学期的ACM都没工夫练习了,反正我知道的Kiki和Ci ...

  7. MCP|MZL|Accurate Estimation of Context- Dependent False Discovery Rates in Top- Down Proteomics 在自顶向下蛋白组学中精确设定评估条件估计假阳性

    一. 概述: 自顶向下的蛋白质组学技术近年来也发展成为高通量蛋白定性定量手段.该技术可以在一次的实验中定性上千种蛋白,然而缺乏一个可靠的假阳性控制方法阻碍了该技术的发展.在大规模流程化的假阳性控制手段 ...

  8. Mysql实例参数优化15个主要参数讲解(原创)

    1.innodb_buffer_pool_size 设置物理内存的60%-80%,反应IO吞吐的最大上限2.innodb_thread_concurrency 线程并发,设置为CPU核心数,如果等于0 ...

  9. ora2pg oracle迁移postgresql工具

    windows下安装 1. 安装strawberry-perl-5.24.3.1-64bit.msi 2. ora2pg-18.2.zip 解压缩cd 进入目录perl Makefile.PLdmak ...

  10. Git Remote (转)

    基本使用 git是一个分布式代码管理工具,所以可以支持多个仓库,在git里,服务器上的仓库在本地称之为remote. 直接clone一个仓库: $: git clone git@search.ued. ...