java web hibernate自学day1
Hibernate
持久层的orm框架,替换jdbc
SSH:Struts(web层) + Spring(业务层) + Hibernate(持久层)
SSM: SpringMVC(web层 ) + Spring(业务层) + Mybatis(持久层)
目录结构
- documentation: 开发文档,api说明
- lib 开发包
- required 依赖包
- optional 可选包
- project 提供的项目
快速开始
-
引入jar包
- 引入数据库驱动包 mysql
- hibernate必须的jar包 required
- hibernate日志记录包 log4j
-
创建表
CREATE TABLE `hiber_cusotmer` (
`cust_id` BIGINT(32) NOT NULL AUTO_INCREMENT COMMENT '客户id',
`cust_name` VARCHAR(32) not null COMMENT '客户公司',
`cust_source` VARCHAR(32) DEFAULT NULL COMMENT '客户信息来源',
`cust_industry` VARCHAR(32) DEFAULT NULL COMMENT '所属行业',
`cust_level` VARCHAR(32) DEFAULT NULL COMMENT '客户级别',
`cust_phone` VARCHAR(64) DEFAULT NULL COMMENT '固定电话',
`cust_mobile` VARCHAR(16) DEFAULT NULL COMMENT '固定电话',
PRIMARY KEY (`cust_id`)
) ENGINE=INNODB AUTO_INCREMENT=1 default charset=utf8;
- 创建实体类,创建getter setter方法
public class Customer {
private Long cust_id;
private String cust_name;
private String cust_source;
private String cust_industry;
private String cust_level;
private String cust_phone;
private String cust_mobile;
}
-
创建映射
需要xml的配置文件来完成,这个配置文件可以任意命名,尽量统一命名规范。类名.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!--建立类与表的映射--> <class name="hjj.web.servlet.Customer" table="hiber_cusotmer"> <!--建立类中的属性与表中的主键对应--> <id name="cust_id" column="cust_id"> <!--本地存储--> <generator class="native"></generator> </id> <!--建立类中的普通属性和表字段的对应--> <property name="cust_industry" column="cust_industry"></property> <property name="cust_name" column="cust_name"></property> <property name="cust_source" column="cust_source"></property> <property name="cust_industry" column="cust_industry"></property> <property name="cust_level" column="cust_level"></property> <property name="cust_phone" column="cust_phone"></property> <property name="cust_mobile" column="cust_mobile"></property> </class> </hibernate-mapping>
-
创建hibernate核心配置文件
名称通常叫hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!--连接数据库的基本参数--> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///hibernate_test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">jianjinhe93</property> <!--配置hibernate的方言--> // 这里根据自己的数据库版本配置,例如mysql8的使用5的无法自动创建表 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!--打印sql语句--> <property name="hibernate.show_sql">true</property> <!--格式化打印--> <property name="hibernate.format_sql">true</property> <!--配置映射文件--> <mapping resource="hjj.web.servlet/Customer.hbm.xml"></mapping> </session-factory> </hibernate-configuration>
-
编写代码
public class HibernateDemo1 { @Test public void demo1(){ // 1. 加载核心配置文件 Configuration configuration = new Configuration().configure(); // 2. 创建sessionFactory,类似于连接池 SessionFactory sessionFactory = configuration.buildSessionFactory(); // 3. 通过sessionFactory获取到session对象 Session session = sessionFactory.openSession(); // 4. 手动开启事务 Transaction transaction = session.beginTransaction(); // 5. 编写代码 Customer customer = new Customer(); customer.setCust_name("lebron"); session.save(customer); // 6. 事务提交 transaction.commit(); // 7. 资源释放 session.close(); } }
常见配置
映射的配置
- class标签
- 用来建立类与表的映射关系
- 属性
- name 类的全路径
- table 表名 类名与表名一致,table可以省略
- id标签
- 用来建立类中的属性与表中主键的对应关系
- 属性
- name. 类中的属性
- column 表中的字段 类属姓名和字段名一致可以省略
- length 长度
- type 类型
type=string
- property标签
- 用来建立类中的普通属性和表字段的对应关系
- 属性
- name
- column
- length
- type
- not-null
- Unique
核心配置
-
配置方式
-
属性文件的方式,此方式不能引入映射文件
hibernate.properties
-
xml文件的方式
hibernate.cfg.xml
-
-
必须的配置
- 连接数据库的基本参数
- 驱动类
- url路径
- 用户名
- 密码
- 连接数据库的基本参数
-
可选的配置
- 显示sql hibernate.show_sql
- 格式化sql hibernate.format_sql
- 自动建表 hibernate.hbm2ddl.auto
- none : 不实用hibernate自动建表
- create: 如果有表,删除重建
- Crate-drop 新建删除,主要做测试用
- update :在原来表的基础上更新
- Validate:校验,如果没有表不会创建表,只会使用数据库中原有的表
API
Configuration:
Hibernate的配置对象
作用:1. 加载核心配置文件。2. 加载映射文件
SessionFactory:
内部维护了hibernate的连接池和hibernate的二级缓存,线程安全的。一般情况下,一个项目通常只需要一个sessionfactiry就够了,单例模式,当需要操作多个数据库时,可以为每一个数据库指定一个sessionFactory。
- 抽取工具类
public class HibernateUtils {
public static final Configuration cfg;
public static final SessionFactory sf;
static {
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
}
public static Session openSession(){
return sf.openSession();
}
}
public class HibernateDemo2 {
@Test
public void demo1(){
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
Customer customer = new Customer();
customer.setCust_name("dwight");
session.save(customer);
transaction.commit();
session.close();
}
}
Session
是一个hibernate和数据库的连接对象,非线程安全,所以不能定义成全局的。
-
保存方法
- Serializable save(Object obj);
-
查询方法
-
T get(class c, Serializable id);
-
T load(class c, Serailizable id);
-
get和load方法的区别
- get采用的是立即加载,执行到这行代码的时候就会马上发送sql语句去查询
- get查询返回的是真实对象本身
- get查询一个找不到的对象返回null
- load采用的延迟加载(懒加载),当真正使用这个对象的时候才会使用,发送sql语句
- load查询返回的是代理对象
- load查询不存在的对象返回ObjectNotFound异常
public void demo2(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); // 使用get方法查询 Customer customer1 = session.get(Customer.class, 1L); System.out.println(customer1); // 使用load方法查询 Customer customer2 = session.load(Customer.class, 2L); transaction.commit(); session.close(); }
-
-
修改方法
-
void update(Object obj)
public void demo3() { Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); // 1.直接创建对象进行修改 Customer customer = new Customer(); customer.setCust_name("kobe"); // 其他为设置的会填充为默认值 session.update(customer); // 2.查询得到对象后修改(推荐) session.get(Customer.class,1L); customer.setCust_name("Carter"); session.update(customer); transaction.commit(); session.close(); }
-
-
删除方法
-
Void delete(Obj object)
public void demo4(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); // 先查询后删除 Customer customer2 = session.get(Customer.class, 2L); session.delete(customer2); transaction.commit(); session.close(); }
-
-
保存或更新
- Void saveOrUpdate()
-
查询所有
public void demo5(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); // 接受HQL,面向对象的查询语言 Query query = session.createQuery("from Customer "); List<Customer> customer_list = query.list(); for (Customer customer : customer_list) { System.out.println(customer); } // 接受SQL NativeQuery sqlQuery = session.createSQLQuery("select * from hibernate_customer"); List<Object> list = sqlQuery.list(); for (Object o : list) { System.out.println(o); } transaction.commit(); session.close(); }
Transaction
- commit()
- rollback()