注解实现映射(注解更方便)
Po--->表 注解非常方便
需要添加包:hibernate-annotations.jar
hibernate-commons-annotation.jar
ejb3-persistence.jar
(1)第一个实例
类User(添加注解)
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private Date birthday;
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
配置文件配置(hibernate.cfg.xml)
<mapping class="hibernate.test.domain.User"></mapping>
测试方法:
引入配置文件方法修改:
Configuration configuration=new Configuration();改为
Configuration configuration=new AnnotationConfiguration();
然后直接测试即可(和前面方法一样)
(2)注解详解
@Entity ―― 将一个类声明为一个实体bean(即一个持久化POJO类)
@Id ―― 注解声明了该实体bean的标识属性(对应表中的主键)。
@Table ―― 注解声明了该实体bean映射指定的表(table),目录(catalog)和schema的名字
@Column ―― 注解声明了属性到列的映射。该注解有如下的属性
* name 可选,列名(默认值是属性名) * unique 可选,是否在该列上设置唯一约束(默认值false)
* nullable 可选,是否设置该列的值可以为空(默认值false)
* insertable 可选,该列是否作为生成的insert语句中的一个列(默认值true)
* updatable 可选,该列是否作为生成的update语句中的一个列(默认值true)
* columnDefinition 可选,为这个特定列覆盖sql ddl片段(这可能导致无法在不同数据库间移植)
* table 可选,定义对应的表(默认为主表)
* length 可选,列长度(默认值255)
* precision 可选,列十进制精度(decimal precision)(默认值0)
@GeneratedValue ―― 注解声明了主键的生成策略。该注解有如下属性
* strategy 指定生成的策略(JPA定义的),这是一个GenerationType。默认是GenerationType. AUTO
* GenerationType.AUTO 主键由程序控制
* GenerationType.TABLE 使用一个特定的数据库表格来保存主键
* GenerationType.IDENTITY 主键由数据库自动生成(主要是自动增长类型)
* GenerationType.SEQUENCE 根据底层数据库的序列来生成主键,条件是数据库支持序列。(这个值要与generator一起使用)
* generator 指定生成主键使用的生成器(可能是orcale中的序列)。
@Transient对应的属性列不在数据库中生成
@Formuta 用一个查询语句动态生成一个类的属性(虚拟的列)
(属性声明:
@Formula("(select count(*) from c_user u where u.id>id)")
private int friendNum;
测试进行获取:
User user1=(User) session.get(User.class, 1);
System.out.println(user1.getId());
System.out.println(user1.getFriendNum());
)
(3)一对一映射
公司和地址之间是一对一关系
第一步:建立类
公司类(Company)
//一对一 注解
@Entity
public class Company {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
@OneToOne(cascade=CascadeType.ALL)
private Address2 address2;
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 Address2 getAddress2() {
return address2;
}
public void setAddress2(Address2 address2) {
this.address2 = address2;
}
}
地址类(Address2)
@Entity
public class Address2 {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String city;
private String street;
private String zipcode;
//mappedBy="address2"映射关系交给了Company中的address2维护
@OneToOne(cascade=CascadeType.ALL,mappedBy="address2")
private Company company;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public void setCompany(Company company) {
this.company = company;
}
public Company getCompany() {
return company;
}
}
第二步:配置文件中添加配置(hibernate.cfg.xml)
<mapping class="hibernate.test.domain.Company"></mapping>
<mapping class="hibernate.test.domain.Address2"></mapping>
第三步:测试
public static void main(String[] args) {
Session session=null;
Transaction tx=null;
try {
session=HibernateAnnocationUtil.getSession();
tx=session.beginTransaction();
Address2 address2=new Address2();
address2.setCity("郑州");
address2.setStreet("商都路");
address2.setZipcode("0371");
Company company=new Company();
company.setName("yizhilain");
company.setAddress2(address2);
session.save(company);
System.out.println(company.getId());
tx.commit();
} catch (Exception e) {
// TODO: handle exception
if(tx!=null)
{
tx.rollback();
}
throw e;
}
finally{
if(session!=null)
{
session.close();
}
}
}
(4)一对多(多对一)映射
部门与员工之间的关系时一对多的关系
第一步:建立类
部门类
@Entity
public class Department2 {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int deptid;
private String dname;
private String location;
//由Employee中的department进行维护。
@OneToMany(mappedBy="department")
private Set<Employee2> employees=new HashSet<Employee2>();
public int getDeptid() {
return deptid;
}
public void setDeptid(int deptid) {
this.deptid = deptid;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public void setEmployees(Set<Employee2> employees) {
this.employees = employees;
}
public Set<Employee2> getEmployees() {
return employees;
}
}
员工类
@Entity
public class Employee2 {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private String job;
@ManyToOne(cascade=CascadeType.ALL)
private Department2 department;
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 String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public void setDepartment(Department2 department) {
this.department = department;
}
public Department2 getDepartment() {
return department;
}
}
第二步:配置文件中添加配置(hibernate.cfg.xml)
<mapping class="hibernate.test.domain.Employee2"></mapping>
<mapping class="hibernate.test.domain.Department2"></mapping>
第三步:测试
public static void main(String[] args) {
Session session=null;
Transaction tx=null;
try {
session=HibernateAnnocationUtil.getSession();
tx=session.beginTransaction();
Department2 department2=new Department2();
department2.setDname("技术部");
department2.setLocation("zhengzhou");
session.save(department2);
Employee2 employee1=new Employee2();
employee1.setName("张三");
Employee2 employee2=new Employee2();
employee2.setName("李四");
employee1.setDepartment(department2);
employee2.setDepartment(department2);
session.save(employee1);
session.save(employee2);
tx.commit();
} catch (Exception e) {
// TODO: handle exception
if(tx!=null)
tx.rollback();
}
finally{
if(session!=null)
session.close();
}
}
(5)多对多映射
学生和课程是多对多的关系。一个学生可以选多门课程,一门课程也可以多个学生选。
第一步:建立类
学生类:
@Table(name="cstudent")
@Entity
public class Student2 {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String sno;
private String name;
@ManyToMany(cascade=CascadeType.ALL)
private Set<Course> courses=new HashSet<Course>();
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getSno() {
return sno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
public Student2( String name) {
super();
this.name = name;
}
public Student2() {
super();
}
public void addCourse(Course course) {
this.courses.add(course);
}
}
课程类:
@Entity
public class Course {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
@ManyToMany(mappedBy="courses")
private Set<Student2> studentsSet=new HashSet<Student2>();
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 Set<Student2> getStudentsSet() {
return studentsSet;
}
public void setStudentsSet(Set<Student2> studentsSet) {
this.studentsSet = studentsSet;
}
}
第二步:配置文件中添加配置(hibernate.cfg.xml)
<mapping class="hibernate.test.domain.Student2"></mapping>
<mapping class="hibernate.test.domain.Course"></mapping>
第三步:测试
public static void main(String[] args) {
// TODO Auto-generated method stub
Session session=null;
Transaction tx=null;
try {
session=HibernateAnnocationUtil.getSession();
tx=session.beginTransaction();
Student2 student2=new Student2();
student2.setName("zhangsan");
Student2 student22=new Student2();
student22.setName("liuyang");
Course course=new Course();
course.setName("语文");
//course.setName("数学");
/*HashSet<Course> courses=new HashSet<Course>();
courses.add(course);
student2.setCourses(courses);*/
student2.addCourse(course);
student22.addCourse(course);
session.save(student2);
session.save(student22);
tx.commit();
} catch (Exception e) {
// TODO: handle exception
if(tx!=null)
tx.rollback();
}
finally{
if(session!=null)
session.close();
}
}