📅  最后修改于: 2023-12-03 15:22:25.266000             🧑  作者: Mango
在使用Hibernate框架时,每个类都需要映射到数据库的表。为了方便我们进行操作,Hibernate提供了注解的方式来进行映射。本篇文章将介绍Hibernate中使用注释教程示例的每个具体类的Hibernate Table。
@Entity
@Table(name = "customer")
public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
//getter and setters
}
上面代码中,注解@Entity表示这是一个实体类,而@Table(name = "customer")表示将该类映射到名为customer的表中。@Id表示该类属性为主键字段,@Column(name = "name")表示将该属性映射到name字段上。
@Entity
@Table(name = "order", uniqueConstraints = {
@UniqueConstraint(columnNames = "order_number") })
public class Order implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "order_number", unique = true, nullable = false)
private String orderNumber;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "customer_id")
private Customer customer;
//getter and setters
}
上面代码中,@UniqueConstraint(columnNames = "order_number")表示orderNumber字段的唯一约束。@ManyToOne表示该字段是多对一的关系,@JoinColumn(name = "customer_id")表示该字段会关联到customer表中的id字段上。
@Entity
@Table(name = "product")
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "price")
private Double price;
//getter and setters
}
上面代码中,@Column(name = "name")表示将该属性映射到name字段上,@Column(name = "price")表示将该属性映射到price字段上。
@Entity
@Table(name = "order_item")
public class OrderItem implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "quantity")
private Integer quantity;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "order_id")
private Order order;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "product_id")
private Product product;
//getter and setters
}
上面代码中,@ManyToOne表示该字段是多对一的关系,@JoinColumn(name = "order_id")表示该字段会关联到order表中的id字段上,@JoinColumn(name = "product_id")表示该字段会关联到product表中的id字段上。
通过上述例子,我们可以看到使用Hibernate的注解方式来进行映射非常方便,大大简化了我们的开发效率。同时,必须注意的是每个具体类的注释方式都不尽相同,需要根据具体情况进行使用。