Hibernate注解(二)
属性注解:
1.1@Id注解:必须,定义了映射到数据库表的主键的属性,一个实体类可以有一个或者多个属性被映射为主键,可置于主键睡醒后者 getXXX()前。注意:若果有多个属性定义为主键属性,该实体必须实现Serializable接口。
1.2@GeneratedValue(strategy=GenerationType,generator=""),两个属性
strategy便是主键生成策略,取值:(1)GenerationType.AUTO:根据底层数据库自动选择(默认,mysql默认是自动增长类型)(2)GenerationType.INDENTITY:根据数据的Identity字段生成,(3)GenerationType.SEQUENCE:使用Sequence来决定主键的取值(oracel,db2)(4)GenerationType.TABLE:使用指定表来决定主键取值,结合@TableGenerator使用。如:
@Id
@TableGenerator(name="tab_cat_gen",allocationSize=1)//用一张表(tab_cat_gen)单独表示主键
@GeneratedValue(Strategy=GenerationType.TABLE)
例子:
1 package com.attributeannotation.entity; 2 3 import java.util.Date; 4 5 import javax.persistence.Column; 6 import javax.persistence.Entity; 7 import javax.persistence.GeneratedValue; 8 import javax.persistence.Id; 9 import javax.persistence.Table; 10 11 import org.hibernate.annotations.GenericGenerator; 12 13 /** 14 * 学生实体类 15 * 16 * @Table(name="",catalog="",schema=""),mysql不支持catalog属性, 17 * 这里的name属性和@Enity的name属性作用是一样的都是给表起一个名字 18 * 19 */ 20 @Entity//(name = "t_students") 21 @Table(name="t_students",schema="hibernate") 22 public class StudentA { 23 24 @Id 25 @GeneratedValue(generator="sid") //generator属性表示生成器,这必须与@GenericGenerator hibernate注解一起使用 26 @GenericGenerator(name="sid",strategy="assigned")//strategy="assigned" 手工赋值 27 @Column(length = 8) // 字符串 28 private String sid;// 学号 29 // @Id/* 联合主键,需要实现Serializable接口*/ 30 // @Column(length = 8)/* 列注解,length属性值字段的长度*/ 31 private String sname;// 姓名 32 private String gender;// 出生日期 33 private Date birthday;// 出生日期 34 private String major;// 专业 35 private Address add;//地址 36 37 public StudentA() { 38 } 39 40 public StudentA(String sid, String sname, String gender, Date birthday, String major, Address add) { 41 this.sid = sid; 42 this.sname = sname; 43 this.gender = gender; 44 this.birthday = birthday; 45 this.major = major; 46 this.add = add; 47 } 48 49 @Id 50 public String getSid() { 51 return sid; 52 } 53 54 public void setSid(String sid) { 55 this.sid = sid; 56 } 57 58 public String getSname() { 59 return sname; 60 } 61 62 public void setSname(String sname) { 63 this.sname = sname; 64 } 65 66 public String getGender() { 67 return gender; 68 } 69 70 public void setGender(String gender) { 71 this.gender = gender; 72 } 73 74 public Date getBirthday() { 75 return birthday; 76 } 77 78 public void setBirthday(Date birthday) { 79 this.birthday = birthday; 80 } 81 82 public String getMajor() { 83 return major; 84 } 85 86 public void setMajor(String major) { 87 this.major = major; 88 } 89 90 public Address getAdd() { 91 return add; 92 } 93 94 public void setAdd(Address address) { 95 this.add = address; 96 } 97 98 99 100 101 102 103 104 }
1 package com.attributeannotation.entity; 2 3 import javax.persistence.Embeddable; 4 5 /*地址类*/ 6 7 @Embeddable /*表示嵌入类,这个类的对象在另一个实体类中充当属性*/ 8 public class Address { 9 10 private String postCode;//邮编 11 private String address;//地址 12 private String phone;//联系电话 13 14 public Address() { 15 } 16 17 public Address(String postCode, String address, String phone) { 18 super(); 19 this.postCode = postCode; 20 this.address = address; 21 this.phone = phone; 22 } 23 24 25 26 public String getPostCode() { 27 return postCode; 28 } 29 public void setPostCode(String postCode) { 30 this.postCode = postCode; 31 } 32 public String getAddress() { 33 return address; 34 } 35 public void setAddress(String address) { 36 this.address = address; 37 } 38 public String getPhone() { 39 return phone; 40 } 41 public void setPhone(String phone) { 42 this.phone = phone; 43 } 44 45 46 47 48 49 }
1 package com.entity; 2 3 import java.util.Date; 4 5 import org.hibernate.Session; 6 import org.hibernate.SessionFactory; 7 import org.hibernate.Transaction; 8 import org.hibernate.cfg.Configuration; 9 import org.hibernate.service.ServiceRegistry; 10 import org.hibernate.service.ServiceRegistryBuilder; 11 import org.hibernate.tool.hbm2ddl.SchemaExport; 12 import org.junit.Test; 13 14 import com.attributeannotation.entity.Address; 15 import com.attributeannotation.entity.StudentA; 16 17 public class TestStudents { 18 19 @Test 20 public void testShemaExport() { 21 // 创建hibernate配置对象 22 Configuration config = new Configuration().configure(); 23 24 // 创建服务注册对象 25 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()) 26 .buildServiceRegistry(); 27 28 // 生成sessionFactory 29 SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); 30 31 SchemaExport export = new SchemaExport(config); 32 33 export.create(true, true); 34 35 } 36 37 @Test 38 public void addStudent() { 39 40 // 创建hibernate配置对象 41 Configuration config = new Configuration().configure(); 42 // 创建服务注册对象 43 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()) 44 .buildServiceRegistry(); 45 // 生成sessionFactory 46 SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); 47 48 //创建session会话 49 Session session = sessionFactory.openSession(); 50 51 Transaction tx = session.beginTransaction(); 52 //创建一个学生对象 53 Address add = new Address("70000","湖北武当山","1230549594"); 54 55 StudentA studentA = new StudentA("s0000001", "张三丰", "男", new Date(), "太极拳", add); 56 session.save(studentA); 57 58 tx.commit(); 59 60 } 61 62 }
上述addStudent方法是测试主键手工赋值生成策略的
1.3@Column-课件GG属性映射到列,使用该注解来覆盖默认值,@Column描述了数据库表中该字段的详细定义,这对于根据JPA注解生成数据库表结构的工具非常有作用。
常用属性:
name:可选,表示数据库表中该字段的名称,默认情形属性名称一致。
nullable:可选,表示该字段是否允许为null,默认是true。
unique:可选,表示该字段是否为唯一标识,默认是false。
length:可选,表示该字段的大小,仅对String类型的字段有效,默认值是255.(如果不是主键不能使用默认值)
insertable:可选,表示在ORM框架执行插入操作时,该字段是否应出现INSERT语句中,默认为true。
updateable:可选,表示在ORM框架执行更新操作时,该字段是否应该出现在UPDATE语句中,默认是true。对于一经创建就不可以更改的字段,该属性非常有用,如对于birthday字段。
1.3@Embedded是注释属性的,表示该属性的类是嵌入类。注意:同时嵌入类也必须标注@Embeddable注解。
1.4@EmbeddedId使用嵌入式主键实现符合主键。注意:嵌入式主键必须实现Serializable接口,必须有默认的public无参数的构造方法,必须覆盖equals和hashCode方法。
例子:
配置文件中hibernate.cfg.xml中mapping标签修改成对应的类
1 <?xml version='1.0' encoding='utf-8'?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD//EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 6 <hibernate-configuration> 7 <session-factory> 8 <property name="connection.username">root</property> 9 <property name="connection.password">mysql</property> 10 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 11 <property name="connection.url">jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=UTF-8</property> 12 13 <!-- 配置数据的库的前缀 --> 14 <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 15 16 <!-- 17 是否把Hibernate运行时的SQL语句输出到控制台,编码阶段便于测试 18 --> 19 <property name="show_sql">true</property> 20 <!-- 21 输出到控制台的SQL语句是否进行排版,便于阅读。建议设置true 22 --> 23 <property name="format_sql">true</property> 24 <!-- 25 可以到帮助由java代码生成数据库脚本,进而生辰具体的表结构。 26 create|update|create-drop|validate 27 --> 28 <property name="hbm2ddl.auto">create</property> 29 30 <mapping class="com.attributeannotation.entity.StudentPKA"/> 31 <!-- <mapping class="com.entity.StudentA"/> --> 32 </session-factory> 33 34 </hibernate-configuration>
主键嵌入类StudentPK:
1 package com.attributeannotation.entity; 2 3 import java.io.Serializable; 4 5 import javax.persistence.Embeddable; 6 7 //学生主键类 8 @Embeddable 9 public class StudentPK implements Serializable { 10 11 private static final long serialVersionUID = 2886826168131509422L; 12 private String id;//身份证号码 13 private String sid;//学号 14 15 public StudentPK(){ 16 } 17 18 public String getId() { 19 return id; 20 } 21 22 public void setId(String id) { 23 this.id = id; 24 } 25 26 public String getSid() { 27 return sid; 28 } 29 30 public void setSid(String sid) { 31 this.sid = sid; 32 } 33 34 @Override 35 public int hashCode() { 36 final int prime = 31; 37 int result = 1; 38 result = prime * result + ((id == null) ? 0 : id.hashCode()); 39 result = prime * result + ((sid == null) ? 0 : sid.hashCode()); 40 return result; 41 } 42 43 @Override 44 public boolean equals(Object obj) { 45 if (this == obj) 46 return true; 47 if (obj == null) 48 return false; 49 if (getClass() != obj.getClass()) 50 return false; 51 StudentPK other = (StudentPK) obj; 52 if (id == null) { 53 if (other.id != null) 54 return false; 55 } else if (!id.equals(other.id)) 56 return false; 57 if (sid == null) { 58 if (other.sid != null) 59 return false; 60 } else if (!sid.equals(other.sid)) 61 return false; 62 return true; 63 } 64 65 66 67 }
学生类StudentPKA:
1 package com.attributeannotation.entity; 2 3 import java.util.Date; 4 5 import javax.persistence.EmbeddedId; 6 import javax.persistence.Entity; 7 import javax.persistence.Table; 8 9 /** 10 * 学生实体类 11 * 12 */ 13 @Entity//(name = "t_students") 14 @Table(name="t_students",schema="hibernate") 15 public class StudentPKA { 16 17 @EmbeddedId 18 private StudentPK pk;//学号 19 //@Id/* 联合主键,需要实现Serializable接口*/ 20 //@Column(length = 8)/* 列注解,length属性值字段的长度*/ 21 private String sname;//姓名 22 private String gender;//出生日期 23 private Date birthday;//出生日期 24 private String major;//专业 25 private String address;//地址 26 27 public StudentPKA() { 28 } 29 30 public StudentPKA(StudentPK sid, String sname, String gender, Date birthday, String major, String address) { 31 this.pk = sid; 32 this.sname = sname; 33 this.gender = gender; 34 this.birthday = birthday; 35 this.major = major; 36 this.address = address; 37 } 38 39 40 41 public StudentPK getPk() { 42 return pk; 43 } 44 45 public void setPk(StudentPK pk) { 46 this.pk = pk; 47 } 48 49 public String getSname() { 50 return sname; 51 } 52 53 public void setSname(String sname) { 54 this.sname = sname; 55 } 56 57 public String getGender() { 58 return gender; 59 } 60 61 public void setGender(String gender) { 62 this.gender = gender; 63 } 64 65 public Date getBirthday() { 66 return birthday; 67 } 68 69 public void setBirthday(Date birthday) { 70 this.birthday = birthday; 71 } 72 73 public String getMajor() { 74 return major; 75 } 76 77 public void setMajor(String major) { 78 this.major = major; 79 } 80 81 public String getAddress() { 82 return address; 83 } 84 85 public void setAddress(String address) { 86 this.address = address; 87 } 88 89 90 91 92 93 94 95 }
测试后,数据库中生成里联合主键。
1.4@Transient可选,表示该属性并非一个数据库表的字段的映射,ORM框架将忽略该属性,如果一个属性并非数据库表的字段映射,就务必将其表示@Transient,否则ORM宽肩默认其注解为@Basic。