注解高级
1.基础映射
(JPA)主键生成策略
@GeneratorValue(strategy=GenerationType.xxx)
GenerationType.IDENTITY: 适宜MySQL、SqlServer有自增长列的数据库。
GenerationType.SEQUENCE:适宜Oracle这种没有自增长有sequence的数据库。
GenerationType.AUTO:让Hibernate根据数据库方言自动选择主键生成策略。
GenerationType.TABLE: 适宜所有的数据库,因为它会单独生成一张表来维护主键生成。
1 package com.rong.entity;
2
3 import java.math.BigDecimal;
4 import java.util.Date;
5
6 import javax.persistence.Column;
7 import javax.persistence.Entity;
8 import javax.persistence.GeneratedValue;
9 import javax.persistence.GenerationType;
10 import javax.persistence.Id;
11 import javax.persistence.Lob;
12 import javax.persistence.Table;
13 import javax.persistence.Temporal;
14 import javax.persistence.TemporalType;
15 import javax.persistence.Transient;
16 @Entity(name="HibernateUser")//说明此类是一个实体类,对应数据库中的一个表(name指定表名)
17 @Table(name="MyUser"//name执行表名
18 ,catalog="hibernate"//指定数据库
19 //,indexes={@Index(columnList="name",name="uk_name",unique=true)}//用于指定表的索引列
20 //,schema="hibernate"//指定数据库 ,两者择一就可以了。
21 //,uniqueConstraints={@UniqueConstraint(columnNames={"name","salary"})}//唯一约束
22 )
23 //@Index是一个索引 columnList:指定列名 unique:是否唯一 name:指定索引的名字
24 public class User {
25 @Id //唯一标志符
26 @GeneratedValue(strategy=GenerationType.AUTO)//主键生成策略
27 @Column(name="hid")
28 private int id;
29 @Column(name="hname"//指定列名
30 ,unique=true//唯一约束
31 ,length=37 //指定长度
32 ,nullable=false //非空约束
33 ,columnDefinition="varchar(50) NOT NULL")//列定义 包括数据类型和约束
34 private String name;
35 @Column(name="hsalary"
36 ,precision=5//有效的总位数。(BigDecimal)会四舍五入
37 ,scale=2 //指定小数位数
38 ,insertable=false//false是不允许插入 true是允许插入
39 ,updatable=true//false是不允许更新 true是允许更新
40 )
41 private BigDecimal salary;
42 @Lob //大文本。映射大的二进制数或者文本
43 /*注意:要修改一下数据库my.ini
44 max_allowed_packet = 1M
45 这个数太小了,存储图片不够。*/
46 private String description;
47 @Temporal(TemporalType.TIMESTAMP)//时间日期处理。修饰日期类型Date
48 /*TemporalType.DATE : yyyy-MM-dd
49 TemporalType.TIME : HH:mm:ss
50 TemporalType.TIMESTAMP : yyyy-MM-dd HH:mm:ss*/
51 private Date birthday;
52 @Transient//不生成数据库字段。指定不是持久化属性
53 //transient关键字修饰不需要序列化的属性,同时用它也能指定不是持久化的属性。
54 private int flag;
55 public int getId() {
56 return id;
57 }
58 public void setId(int id) {
59 this.id = id;
60 }
61 public String getName() {
62 return name;
63 }
64 public void setName(String name) {
65 this.name = name;
66 }
67 public BigDecimal getSalary() {
68 return salary;
69 }
70 public void setSalary(BigDecimal salary) {
71 this.salary = salary;
72 }
73 public String getDescription() {
74 return description;
75 }
76 public void setDescription(String description) {
77 this.description = description;
78 }
79 public Date getBirthday() {
80 return birthday;
81 }
82 public void setBirthday(Date birthday) {
83 this.birthday = birthday;
84 }
85 public int getFlag() {
86 return flag;
87 }
88 public void setFlag(int flag) {
89 this.flag = flag;
90 }
91 }
2.主键映射
A.一个主键
B.多个主键(联合主键)
1 package com.rong.entity;
2
3 import java.io.Serializable;
4 import java.math.BigDecimal;
5
6 import javax.persistence.Entity;
7 import javax.persistence.Id;
8 import javax.persistence.Table;
9 @Entity
10 @Table(name="MyUser")
11 public class User implements Serializable{
12 private static final long serialVersionUID = 6513230274782818419L;
13 //多主键的时候 不能使用@GeneratedValue,还需要实现Serializable接口
14 @Id
15 private int id;
16 @Id
17 private String name;
18 private BigDecimal salary;
19 public int getId() {
20 return id;
21 }
22 public void setId(int id) {
23 this.id = id;
24 }
25 public String getName() {
26 return name;
27 }
28 public void setName(String name) {
29 this.name = name;
30 }
31 public BigDecimal getSalary() {
32 return salary;
33 }
34 public void setSalary(BigDecimal salary) {
35 this.salary = salary;
36 }
37 }
3.联合主键
A.分开写法
如上所示。
B.组合写法
把需要作为主键的字段组合成一个类,并且该类必须实现Serializable接口。
1 package com.rong.entity; 2 3 import java.io.Serializable; 4 5 import javax.persistence.Column; 6 7 public class Name implements Serializable{ 8 private static final long serialVersionUID = -980163939442679798L; 9 @Column(name="first_name")//可在此处修改列名 10 private String firstName; 11 @Column(name="last_name")//可在此处修改列名 12 private String lastName; 13 public String getFirstName() { 14 return firstName; 15 } 16 public void setFirstName(String firstName) { 17 this.firstName = firstName; 18 } 19 public String getLastName() { 20 return lastName; 21 } 22 public void setLastName(String lastName) { 23 this.lastName = lastName; 24 } 25 }
在hibernate.cfg.xml中配置实体类
1 package com.rong.entity;
2
3 import javax.persistence.AttributeOverride;
4 import javax.persistence.AttributeOverrides;
5 import javax.persistence.Column;
6 import javax.persistence.EmbeddedId;
7 import javax.persistence.Entity;
8 @Entity
9 public class Person {
10 @EmbeddedId
11 //也可在此处修改列名(列名取决于本类的修改)
12 @AttributeOverrides(value={@AttributeOverride(column=@Column(name="f_n"), name = "firstName"),
13 @AttributeOverride(column = @Column(name="l_n"), name = "lastName")})
14 private Name name;
15
16 public Name getName() {
17 return name;
18 }
19
20 public void setName(Name name) {
21 this.name = name;
22 }
23 }
4.集合映射
A.List集合(List集合生成表的主键列:【外键列 + 排序列】)
list里面放的是系统自带类型:
1 package com.rong.entity;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import javax.persistence.CollectionTable;
7 import javax.persistence.ElementCollection;
8 import javax.persistence.Entity;
9 import javax.persistence.FetchType;
10 import javax.persistence.GeneratedValue;
11 import javax.persistence.GenerationType;
12 import javax.persistence.Id;
13 import javax.persistence.OrderColumn;
14 import javax.persistence.Table;
15 @Entity
16 @Table(name="MyUser")
17 public class User{
18 @Id
19 @GeneratedValue(strategy=GenerationType.AUTO)
20 private int id;
21 private String name;
22 @ElementCollection(targetClass=String.class// 指定集合中元素的类型
23 ,fetch=FetchType.LAZY // 加载策略,懒加载
24 )
25 @CollectionTable(name="MyAddress") // 指定集合生成的表
26 @OrderColumn(name="address") // 指定排序列
27 private List addr=new ArrayList();
28 @Override
29 public String toString() {
30 return "User [id=" + id + ", name=" + name + ", addr=" + addr + "]";
31 }
32 public List getAddr() {
33 return addr;
34 }
35 public void setAddr(List addr) {
36 this.addr = addr;
37 }
38 public int getId() {
39 return id;
40 }
41 public void setId(int id) {
42 this.id = id;
43 }
44 public String getName() {
45 return name;
46 }
47 public void setName(String name) {
48 this.name = name;
49 }
50 }
list里面放的是自定义类型:
1 package com.rong.entity; 2 3 import javax.persistence.Embeddable; 4 5 @Embeddable 6 public class Address { 7 public Address(String addr) { 8 super(); 9 this.addr = addr; 10 } 11 12 public Address() { 13 super(); 14 } 15 16 private String addr; 17 18 19 public String getAddr() { 20 return addr; 21 } 22 23 public void setAddr(String addr) { 24 this.addr = addr; 25 } 26 }
1 package com.rong.entity; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import javax.persistence.CollectionTable; 7 import javax.persistence.ElementCollection; 8 import javax.persistence.Entity; 9 import javax.persistence.FetchType; 10 import javax.persistence.GeneratedValue; 11 import javax.persistence.GenerationType; 12 import javax.persistence.Id; 13 import javax.persistence.OrderColumn; 14 import javax.persistence.Table; 15 @Entity 16 @Table(name="MyUser") 17 public class User{ 18 @Id 19 @GeneratedValue(strategy=GenerationType.AUTO) 20 private int id; 21 private String name; 22 @ElementCollection(targetClass=Address.class// 指定集合中元素的类型 23 ,fetch=FetchType.LAZY // 加载策略,懒加载 24 ) 25 @CollectionTable(name="MyAddress") // 指定集合生成的表 26 @OrderColumn(name="address_sort") // 指定排序列 27 private List addr=new ArrayList(); 28 @Override 29 public String toString() { 30 return "User [id=" + id + ", name=" + name + ", addr=" + addr + "]"; 31 } 32 public List getAddr() { 33 return addr; 34 } 35 public void setAddr(List addr) { 36 this.addr = addr; 37 } 38 public int getId() { 39 return id; 40 } 41 public void setId(int id) { 42 this.id = id; 43 } 44 public String getName() { 45 return name; 46 } 47 public void setName(String name) { 48 this.name = name; 49 } 50 }
B.Set集合(Set集合生成表的主键列:【外键列 + Set集合的元素列 .. 】)
set里面放的是系统自带类型:
Set集合生成表默认是没有主键列的。如果想要生成主键列,需要为Set集合添加非空约束!
1 package com.rong.entity; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 6 import javax.persistence.CollectionTable; 7 import javax.persistence.Column; 8 import javax.persistence.ElementCollection; 9 import javax.persistence.Entity; 10 import javax.persistence.FetchType; 11 import javax.persistence.GeneratedValue; 12 import javax.persistence.GenerationType; 13 import javax.persistence.Id; 14 import javax.persistence.Table; 15 @Entity 16 @Table(name="MyUser") 17 public class User{ 18 @Id 19 @GeneratedValue(strategy=GenerationType.AUTO) 20 private int id; 21 private String name; 22 @ElementCollection(targetClass=String.class// 指定集合中元素的类型 23 ,fetch=FetchType.LAZY // 加载策略,懒加载 24 ) 25 @CollectionTable(name="MyAddress") // 指定集合生成的表 26 @Column(nullable=false)// 添加非空约束 27 private Setaddr=new HashSet (); 28 @Override 29 public String toString() { 30 return "User [id=" + id + ", name=" + name + ", addr=" + addr + "]"; 31 } 32 33 public Set getAddr() { 34 return addr; 35 } 36 37 public void setAddr(Set addr) { 38 this.addr = addr; 39 } 40 41 public int getId() { 42 return id; 43 } 44 public void setId(int id) { 45 this.id = id; 46 } 47 public String getName() { 48 return name; 49 } 50 public void setName(String name) { 51 this.name = name; 52 } 53 }
1 package com.rong.test; 2 3 import java.util.Set; 4 5 import org.hibernate.Session; 6 import org.hibernate.SessionFactory; 7 import org.hibernate.Transaction; 8 import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 9 import org.hibernate.cfg.Configuration; 10 import org.hibernate.service.ServiceRegistry; 11 import org.junit.Test; 12 13 import com.rong.entity.User; 14 15 public class HibernateTest { 16 @Test 17 public void test1(){ 18 Configuration configuration=new Configuration().configure(); 19 ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); 20 SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); 21 Session session = sessionFactory.openSession(); 22 Transaction transaction = session.beginTransaction(); 23 24 User user=new User(); 25 user.setName("OK"); 26 Setaddr = user.getAddr(); 27 addr.add("中国"); 28 addr.add("法国"); 29 addr.add("英国"); 30 addr.add("美国"); 31 32 session.save(user); 33 //查找user 34 User findUser = (User) session.get(User.class, 1); 35 System.out.println(findUser); 36 transaction.commit(); 37 session.close(); 38 sessionFactory.close(); 39 } 40 }
set里面放的是自定义类型:
1 package com.rong.entity; 2 3 import javax.persistence.Embeddable; 4 5 @Embeddable 6 public class Address { 7 public Address(String addr) { 8 super(); 9 this.addr = addr; 10 } 11 12 public Address() { 13 super(); 14 } 15 16 private String addr; 17 18 19 public String getAddr() { 20 return addr; 21 } 22 23 public void setAddr(String addr) { 24 this.addr = addr; 25 } 26 27 @Override 28 public String toString() { 29 return "Address [addr=" + addr + "]"; 30 } 31 }
1 package com.rong.entity; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 6 import javax.persistence.CollectionTable; 7 import javax.persistence.ElementCollection; 8 import javax.persistence.Entity; 9 import javax.persistence.FetchType; 10 import javax.persistence.GeneratedValue; 11 import javax.persistence.GenerationType; 12 import javax.persistence.Id; 13 import javax.persistence.Table; 14 @Entity 15 @Table(name="MyUser") 16 public class User{ 17 @Id 18 @GeneratedValue(strategy=GenerationType.AUTO) 19 private int id; 20 private String name; 21 @ElementCollection(targetClass=Address.class// 指定集合中元素的类型 22 ,fetch=FetchType.LAZY // 加载策略,懒加载 23 ) 24 @CollectionTable(name="MyAddress") // 指定集合生成的表 25 private Set addr=new HashSet(); 26 @Override 27 public String toString() { 28 return "User [id=" + id + ", name=" + name + ", addr=" + addr + "]"; 29 } 30 31 public Set getAddr() { 32 return addr; 33 } 34 35 public void setAddr(Set addr) { 36 this.addr = addr; 37 } 38 39 public int getId() { 40 return id; 41 } 42 public void setId(int id) { 43 this.id = id; 44 } 45 public String getName() { 46 return name; 47 } 48 public void setName(String name) { 49 this.name = name; 50 } 51 }
1 package com.rong.test; 2 3 import java.util.List; 4 import java.util.Set; 5 6 import org.hibernate.Session; 7 import org.hibernate.SessionFactory; 8 import org.hibernate.Transaction; 9 import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 10 import org.hibernate.cfg.Configuration; 11 import org.hibernate.service.ServiceRegistry; 12 import org.junit.Test; 13 14 import com.rong.entity.Address; 15 import com.rong.entity.User; 16 17 public class HibernateTest { 18 @Test 19 public void test1(){ 20 Configuration configuration=new Configuration().configure(); 21 ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); 22 SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); 23 Session session = sessionFactory.openSession(); 24 Transaction transaction = session.beginTransaction(); 25 26 User user=new User(); 27 user.setName("OK"); 28 Set addr = user.getAddr(); 29 addr.add(new Address("中国")); 30 addr.add(new Address("美国")); 31 addr.add(new Address("英国")); 32 addr.add(new Address("德国")); 33 34 session.save(user); 35 //查找user 36 User findUser = (User) session.get(User.class, 1); 37 System.out.println(findUser); 38 transaction.commit(); 39 session.close(); 40 sessionFactory.close(); 41 } 42 }
C.Map集合(Map集合生成表的主键列:【外键列 + Map的Key】)
value值是系统自带的类型
1 package com.rong.entity;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 import javax.persistence.CollectionTable;
7 import javax.persistence.ElementCollection;
8 import javax.persistence.Entity;
9 import javax.persistence.FetchType;
10 import javax.persistence.GeneratedValue;
11 import javax.persistence.GenerationType;
12 import javax.persistence.Id;
13 import javax.persistence.MapKeyColumn;
14 import javax.persistence.Table;
15 @Entity
16 @Table(name="MyUser")
17 public class User{
18 @Id
19 @GeneratedValue(strategy=GenerationType.AUTO)
20 private int id;
21 private String name;
22 @ElementCollection(targetClass=String.class// 指定集合中元素value值的类型
23 ,fetch=FetchType.LAZY // 加载策略,懒加载
24 )
25 @CollectionTable(name="MyMap") // 指定集合生成的表
26 @MapKeyColumn(name="map_key")//指定map的key生成的列
27 private Map map=new HashMap();//成员变量起什么名字,列名就是什么
28
29 public int getId() {
30 return id;
31 }
32 public void setId(int id) {
33 this.id = id;
34 }
35 public String getName() {
36 return name;
37 }
38 public void setName(String name) {
39 this.name = name;
40 }
41 public Map getMap() {
42 return map;
43 }
44 public void setMap(Map map) {
45 this.map = map;
46 }
47 @Override
48 public String toString() {
49 return "User [id=" + id + ", name=" + name + ", map=" + map + "]";
50 }
51 }
1 package com.rong.test; 2 3 import java.util.Map; 4 import java.util.Set; 5 6 import org.hibernate.Session; 7 import org.hibernate.SessionFactory; 8 import org.hibernate.Transaction; 9 import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 10 import org.hibernate.cfg.Configuration; 11 import org.hibernate.service.ServiceRegistry; 12 import org.junit.Test; 13 14 import com.rong.entity.User; 15 16 public class HibernateTest { 17 @Test 18 public void test1(){ 19 Configuration configuration=new Configuration().configure(); 20 ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); 21 SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); 22 Session session = sessionFactory.openSession(); 23 Transaction transaction = session.beginTransaction(); 24 25 User user=new User(); 26 user.setName("kobe"); 27 Mapmap = user.getMap(); 28 map.put("height", "198"); 29 map.put("weight", "123"); 30 map.put("hobby", "basketball"); 31 session.save(user); 32 //查找user 33 User findUser = (User) session.get(User.class, 1); 34 System.out.println(findUser); 35 transaction.commit(); 36 session.close(); 37 sessionFactory.close(); 38 } 39 }
value值是自定义的类型
注意:类名(表名)、成员变量名(列名)不能使用数据库的关键字!!!
1 package com.rong.entity;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 import javax.persistence.CollectionTable;
7 import javax.persistence.ElementCollection;
8 import javax.persistence.Entity;
9 import javax.persistence.FetchType;
10 import javax.persistence.GeneratedValue;
11 import javax.persistence.GenerationType;
12 import javax.persistence.Id;
13 import javax.persistence.MapKeyColumn;
14 import javax.persistence.Table;
15 @Entity
16 @Table(name="MyUser")
17 public class User{
18 @Id
19 @GeneratedValue(strategy=GenerationType.AUTO)
20 private int id;
21 private String name;
22 @ElementCollection(targetClass=Infos.class// 指定集合中元素value值的类型
23 ,fetch=FetchType.LAZY // 加载策略,懒加载
24 )
25 @CollectionTable(name="MyMap") // 指定集合生成的表
26 @MapKeyColumn(name="map_key")//指定map的key生成的列
27 private Map<String,Infos> infoMap=new HashMap();//成员变量起什么名字,列名就是什么
28
29 public int getId() {
30 return id;
31 }
32 public void setId(int id) {
33 this.id = id;
34 }
35 public String getName() {
36 return name;
37 }
38 public void setName(String name) {
39 this.name = name;
40 }
41 public Map getInfoMap() {
42 return infoMap;
43 }
44 public void setInfoMap(Map infoMap) {
45 this.infoMap = infoMap;
46 }
47 @Override
48 public String toString() {
49 return "User [id=" + id + ", name=" + name + ", infoMap=" + infoMap + "]";
50 }
51 }
1 package com.rong.entity; 2 3 import javax.persistence.Embeddable; 4 5 @Embeddable 6 public class Infos { 7 public Infos(String describe) { 8 super(); 9 this.intro = describe; 10 } 11 12 public Infos() { 13 super(); 14 } 15 16 private String intro; 17 18 public String getDescribe() { 19 return intro; 20 } 21 22 public void setDescribe(String describe) { 23 this.intro = describe; 24 } 25 26 @Override 27 public String toString() { 28 return "Information [describe=" + intro + "]"; 29 } 30 }
User [id=1, name=huge, infoMap={weight=Information [describe=65], height=Information [describe=182], hobby=Information [describe=movie]}]