下面通过一个实际的列子来展示Hibernate的基本用法。
实例:
package com.ydoing.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.MapKeyClass;
import javax.persistence.MapKeyColumn;
import javax.persistence.OrderColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.hibernate.annotations.Formula;
@Entity
@Table(name = "person")
public class Person {
// 主键为ID,最好设置为包装类型Integer
@Id
@Column(name = "person_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
// 指定字符长度
@Column(name = "name", length = 50, nullable = false)
private String name;
@Column(name = "age")
private int age;
// 也可以不指定列名,默认为类的属性名
@Column
private String sex;
// @Transient表示不用持久化
@Transient
private String alias;
// @Lob表示大数据类型,FetchType.LAZY表示延迟加载,减少性能开销
@Lob
@Basic(fetch = FetchType.LAZY)
private byte[] image;
// 指定为日期类型
@Temporal(TemporalType.DATE)
private Date birthdate;
// 属性动态生成
@Formula("(select concat(p.name, p.age, p.sex) from person p where p.person_id = person_id)")
private String profile;
// List集合类型
// 需要显示初始化集合的类型
@ElementCollection(targetClass = String.class)
@CollectionTable(name = "pet_inf",// 指定表名
// 用于映射外键
joinColumns = @JoinColumn(name = "person_id", nullable = false))
@Column(name = "pet_name")
@OrderColumn(name = "list_order")
private List<String> pets = new ArrayList<>();
// 数组属性
@ElementCollection(targetClass = String.class)
@CollectionTable(name = "school_inf", joinColumns = @JoinColumn(name = "person_id", nullable = false))
@Column(name = "school_name")
@OrderColumn(name = "array_order")
private String[] schools;
// Set集合属性,Set是无序的,不可重复的,因此Set集合属性无须使用@OrderColumn注解映射集合的索引列
@ElementCollection(targetClass = String.class)
@CollectionTable(name = "car_inf", joinColumns = @JoinColumn(name = "person_id", nullable = false))
@Column(name = "car_name")
private Set<String> cars = new HashSet<>();// 必须指定接口实现类
// Map集合属性
@ElementCollection(targetClass = Float.class)
@CollectionTable(name = "salary_inf", joinColumns = @JoinColumn(name = "person_id", nullable = false))
// 指定key的类型
@MapKeyColumn(name = "salary_type")
@MapKeyClass(String.class)
// 映射Map的value
@Column(name = "money")
private Map<String, Float> payroll = new HashMap<>(); // 必须指定接口实现类
// 映射组件属性,所谓组件的意思是:不是基本数据类型,而是自定义的复合类型,且不是持久化实体
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Map<String, Float> getPayroll() {
return payroll;
}
public void setPayroll(Map<String, Float> payroll) {
this.payroll = payroll;
}
public String[] getSchools() {
return schools;
}
public void setSchools(String[] schools) {
this.schools = schools;
}
public String getSex() {
return sex;
}
public Set<String> getCars() {
return cars;
}
public void setCars(Set<String> cars) {
this.cars = cars;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public Person() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
public List<String> getPets() {
return pets;
}
public void setPets(List<String> pets) {
this.pets = pets;
}
public void setId(Integer id) {
this.id = id;
}
}
组件类
package com.ydoing.domain;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import org.hibernate.annotations.Parent;
@Embeddable
public class Address {
@Column(name = "person_province")
private String province;
@Column(name = "person_city")
private String city;
public Address() {
}
// 属于哪个实体组件
@Parent
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Address(String province, String city) {
super();
this.province = province;
this.city = city;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
测试:
package com.ydoing.test;
import java.util.Arrays;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.ydoing.domain.Address;
import com.ydoing.domain.Person;
public class Main {
public static void main(String[] args) {
Configuration conf = new Configuration();
conf.configure();
// ServiceRegistry serviceRegistry = new
// ServiceRegistryBuilder().applySettings(conf.getProperties())
// .buildServiceRegistry();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties())
.build();
SessionFactory factory = conf.buildSessionFactory(serviceRegistry);
Session session = factory.openSession();
Person person = new Person();
person.setName("Jack");
person.setAge(22);
person.setSex("男");
// 不会持久化
person.setAlias("Arron");
// List属性
String[] array = { "cat", "dog", "snake" };
List<String> pets = Arrays.asList(array);
person.setPets(pets);
// 数组属性
String[] schools = { "清华", "北大" };
person.setSchools(schools);
// Set集合属性
person.getCars().add("奥迪");
person.getCars().add("大众");
// Map属性
person.getPayroll().put("基本工资", (float) 5000);
person.getPayroll().put("绩效", (float) 3000);
person.setAddress(new Address("浙江", "杭州"));
Transaction tx = session.getTransaction();
tx.begin();
session.save(person);
Person p = (Person) session.load(Person.class, 12);
System.out.println(p.getProfile());
tx.commit();
session.close();
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-09 22:05:57