慕课网Hibernate学习笔记
开发环境
- eclipse mars
- hibernate toos
最简单的例子
创建java Project
导入相关依赖
- 导入hibernate-re...\lib\required中的jar包
- 导入mysql驱动
- 导入Junit4包
- 创建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="connection.user">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
- 创建持久化类(javabean)
- 公有
- 提供不带参数的的构造方法
- 属性私有
- 有setter和getter
public class Student {
private int id;
private String name;
private String sex;
private int age;
public Student() {
}
public Student(int id, String name, String sex, int age) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
}
- 创建对象关系映射文件(*.hbm.xml)
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-10-2 16:35:18 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="Student" table="STUDENT">
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="sex" type="java.lang.String">
<column name="SEX" />
</property>
<property name="age" type="int">
<column name="AGE" />
</property>
</class>
</hibernate-mapping>
- 将映射添加到hibernate.cfg.xml
<mapping resource="Student.hbm.xml"/>
- 创建JUnit测试类
public class StudentTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init(){
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
@After
public void destroy(){
transaction.commit();
session.close();
sessionFactory.close();
}
@Test
public void testSaveStudent() {
Student student = new Student(2, "老王", "男", 13);
session.save(student);
}
}
- 运行测试即可将数据存入数据库
Hibernate相关介绍
hibernat.cfg.xml属性介绍
hibernat.show_sql:(true|false)是否输出sql语句到控制台
hibernat.format_sql: (true|false)是否对输出的sql语句进行排版
hbm2ddl.auto:(create|update|create-drop|va|idate)
create每次插入都会删除原来的表,update会更新原来的表hibernate.default_schema:(hibernate)设置默认数据库,会在sql语句中的表名前加入前缀
hibernate.dialect:(org.hibernate.dialect.MySQLDialect)数据库方言,可针对特定数据库进行优化
hibernate.current_session_contex_class:(thread|jta):
用于指定getCurrentSession是获取本地事务还是全局事务
session
SessionFactory一个系统一般只创建一个
openSession每次获取的事务时不同事务
getCurrentSession获取的是同一个事务,会自动关闭
通过session进行增删改查
操作前需开启transaction,完成后提交transaction
*.hbm.xml配置文件介绍
<hibernate-mapping
schema="schema_name"
catalog="catalog_name"//目录mysql不支持
default_cascade="cascade_style"//级联风格
default_access="field|property|ClassName"//访问策略
default-lazy="true|false"//加载策略
package="packageName"
>
<id>
<generator class="assigned|native|increment"/>
</id>
//组件属性
<component name="address" class="">
<property name="" column></property>
</component>
增删改查
- save
- update
- delete
- get //一次性获取
- load // 懒加载
一对多
实体类中设置多方的set
在一方的映射文件中设置
<set name="students" table="student" lazy="true" inverse="true" cascade="all">//inverse=true表示由多方维护关联关系(多方add元素后,插入时不会出现update)
//cascade="all|save-update|delete|none"
<key column="gid"></key>
<one-to-many class="student">
</set>
多对一
在实体类中设置一方的实例
在多方映射文件中设置
<many-to-one name="grade" class="Grade" conlumn = "gid"></many-to-one>
HQL语句
select xxx from xxx where xxx group by xxx having xxx order by xxx
使用方法
大小写敏感
简单例子
@Test
public void testQuery(){
String hql = "from Student as s";
List<Student> students = session.createQuery(hql).list();
for(Student student : students){
System.out.println(student);
}
}
- 返回Object[]
//只选择一个属性则返回object
@Test
public void testSelect(){
String hql = "select s.id, s.name from Student as s";
Query<Object[]> query = session.createQuery(hql);
List<Object[]> list = query.list();
for(Object[] objects : list){
System.out.println(objects[0]);
System.out.println(objects[1]);
}
}
- 返回list
@Test
public void testSelectWithList(){
String hql = "select new list(s.id, s.name) from Student as s";
Query query = session.createQuery(hql);
List<List> lists = query.list();
for(List list : lists){
System.out.println(list.get(0));
System.out.println(list.get(1));
}
}
- 返回自定义类
//需要有相应的构造方法
String hql = "select new Student(s.id, s.name) from Student as s"
List<Student> lists = query.list();
没有指定构造器会调用默认构造器即无参构造函数
集合运算"from grade g where g.students is not empty";
获取单个对象
@Test
public void testGetOne(){
String hql="from Student as s where s.id=1";
Query query = session.createQuery(hql);
Student student = (Student) query.uniqueResult();
System.out.println(student.getName());
}
Hibernate 缓存
一级缓存
与session相同的生命周期
示例代码
@Test
public void testCache(){
Student student1 = session.get(Student.class, 1);
//清除指定对象缓存
session.evict(student1);
//清除所有缓存
session.clear();
Student student2 = session.get(Student.class, 1);
//list()不使用缓存
String hql = "from Student";
Query query = session.createQuery(hql);
List<Student> students = query.list();
//iterator 先从数据库获取所有id,判断缓存中是否有对应记录,若有则直接使用缓存
Iterator iterator = query.iterate();
while(iterator.hasNext()){
Student student = (Student) iterator.next();
System.out.println(student.getName());
}
}
Hibernate注解
类级别注解
- @Entity(name="tableName")
- @table(name="", catalog="", schema="")
- @Embeddable // 在嵌入类上添加(如Address类)
属性级别注解
可写在属性上也可以写在get方法上
@Id
//多个属性Id实体类需要实现serializable接口
//字符串主键需要通过@Column指定长度@GeneratedValue(strategy=(), generator="")
//主键生成策略
@GeneratedValue(generator="id")
@GenericGenerator(name="id", strategy="assigned")
- @Column(length="", name="", nullable="", insertable="", unique="", updateable="")
- @Embedded
//嵌入类需要@Embeddable - @EmbeddedId
//嵌入类(需要@Embeddable,实现Serializable接口,有无参构造方法,覆盖equals,hashCode)作为主键 - @Transient
//忽略某个字段,不映射到数据库
关联映射注解
@OneToOne(cascade=CascadeType.ALl, mappedBy="id")
//mappedBy设置主控放
@JoinColumn(name="id", unique=true)@ManyTOOne(cascade={CascadeType.ALL} fetch=FetchType.EAGER)
//fetch抓取策略默认积极
@JoinColumn(name="gid", referenceColumnName="gid")@OneToMany(cascade={CascadeType.ALL} fetch=FetchType.LAZY)
@JoinColumn(name="gid")@ManyToMany(mappedBy="")
@JoinTable(name="",JoinColumns="",
inverseJoinColumns={@JoinColumn(name="tid")})