JavaWeb系列7: Hibernate
本文是作者的读博客笔记和心得整理,也引用了一些比较好的博客文章,部分内容来源于网络,如有侵权,请联系作者。
什么是Hibernate
这是一种ORM的框架,全称是Object Relative DataBase-Mapping,在java对象和关系数据库之间建立某种映射,直接存取java对象.
属于在MVC中的数据持久层,也就是DAO层.
DAO层主要过程是:
操作XML,将数据封装到XML文件上,读写XML文件实现CURD
或者使用JDBC连接数据库,实现CURD
Hibernate提供的简化就是JavaBean对象和数据表中的列存在映射关系,这样就可以避免写SQL语句了.
示例讲解一个Hibernate配置
先编写一个对象
public class User {
private int id;
private String username;
private String password;
private String cellphone;
//各种setter和getter
}
然后配置一个XML
<!--在domain包下-->
<hibernate-mapping package="zhongfucheng.domain">
<!--类名为User,表名也为User-->
<class name="User" table="user">
<!--主键映射,属性名为id,列名也为id-->
<id name="id" column="id">
<!--根据底层数据库主键自动增长-->
<generator class="native"/>
</id>
<!--非主键映射,属性和列名一一对应-->
<property name="username" column="username"/>
<property name="cellphone" column="cellphone"/>
<property name="password" column="password"/>
</class>
</hibernate-mapping>
注意name是类中的属性,column是表中的列名.
看一个入门案例
public static void main(String[] args) {
//创建对象
User user = new User();
user.setPassword("123");
user.setCellphone("122222");
user.setUsername("nihao");
//获取加载配置管理类
Configuration configuration = new Configuration();
//不给参数就默认加载hibernate.cfg.xml文件,
configuration.configure();
//创建Session工厂对象
SessionFactory factory = configuration.buildSessionFactory();
//得到Session对象
Session session = factory.openSession();
//使用Hibernate操作数据库,都要开启事务,得到事务对象
Transaction transaction = session.getTransaction();
//开启事务
transaction.begin();
//把对象添加到数据库中
session.save(user);
//提交事务
transaction.commit();
//关闭Session
session.close();
}
同时Hibernate还提供了一些常用的Session的方法来实现:
public interface IEmployeeDao {
void save(Employee emp);
void update(Employee emp);
Employee findById(Serializable id);
List<Employee> getAll();
List<Employee> getAll(String employeeName);
List<Employee> getAll(int index, int count);
void delete(Serializable id);
}
同时当然也支持注解开发方式,而且比较常用:
@Entity // 定义了一个实体
@Table(name="t_book",catalog="hibernateTest")
public class Book {
@Id // 这表示一个主键
// @GeneratedValue 相当于native主键生成策略
@GeneratedValue(strategy=GenerationType.IDENTITY) // 相当于identity主键生成策略
private Integer id; // 主键
@Column(name="c_name", length=30, nullable=true)
private String name;
@Temporal(TemporalType.TIMESTAMP) // 是用来定义日期类型
private Date publicationDate; // 出版日期
@Type(type="double") // 允许你去指定Hibernate里面的一些类型
private Double price; // 价格,如果没有添加注解,也会自动的生成在表中
对于PO类的使用
@Entity是用来声明一个实体
@Table来声明一个表
@id声明一个主键,常常和@GeneratedValue一起,表面一个主键的声明策略
@Id表示这是一个主键
@Column定义一个列
@Temporal声明日期类型
@Transient表面这个属性不生成在表中
下面是一个比较简单的测试类:
public class HibernateAnnotationTest {
// 测试PO的注解开发
@Test
public void test1() {
Session session = HibernateUtils.openSession();
session.beginTransaction();
Book b = new Book();
b.setName("情书");
b.setPrice(56.78);
b.setPublicationDate(new Date());
session.save(b);
session.getTransaction().commit();
session.close();
}
}
还有@OneToMany和@ManyToOne这两个注解用来生成外键.