java Hibernate 学习

导包

hibernate 下载地址 http://hibernate.org/

requir 文件夹为必须要导入的包

  • 可选包 有c3p0 包 (数据库连接池)

环境

测试环境
  • myeclipse java project

配置

<?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.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql:///test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <!-- 方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- 数据连接池 -->
        <property name="hibernate.c3p0.max_size">2</property>
        <property name="hibernate.c3p0.min_size">2</property>
        <property name="hibernate.c3p0.timeout">5000</property>
        <property name="hibernate.c3p0.max_statements">100</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        <property name="hibernate.c3p0.acquire_increment">2</property>
        <property name="hibernate.c3p0.validate">false</property>

        <!-- 其他配置 -->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.current_session_context_class">thread</property>

        <!-- 映射文件的配置 -->
        <mapping resource="com/norwaya/pojo/User.hbm.xml"/>
        <mapping resource="com/norwaya/pojo/Address.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

核心代码

Configuration cfg = new Configuration().configure();
        ServiceRegistry serviceRegistry= new
                ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry(); 
        SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry);

Session session = sessionFactory.getCurrentSession();//session 是一切操作的核心


session.beginTransaction();
// CRUD 操作 etc.
...
session.getTransaction().commit();

多对一操作

Address.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 package="com.norwaya.pojo">
    <class name="Address" table="address">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="info" />

        <many-to-one name="user" class="User" column="user_id"/>
    </class>
</hibernate-mapping>
User.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 package="com.norwaya.pojo">
    <class name="User" table="User">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name" />
        <property name="age"/>
        <property name="birthday"/>
        <set name="set" inverse="true" cascade="delete" fetch="join" order-by="id desc"> 
            <key column="user_id"/>
            <one-to-many class="Address"/>
        </set>
    </class>
</hibernate-mapping>

fetch :查询的时候 join 进来 address ,获取address 的时候,不用再次获取
order-by:排序配置
inverse:当自身改变的时候不去更新操作
cascade:值为delete 的时候,级联删除(删除user的时候,会删除address)


一对一的数据操作
Card.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 package="com.kaishengit.pojo">
    <class name="Card" table="t_card">
        <id name="id" column="id">
            <generator class="foreign">
                <param name="property">person</param>
            </generator>
        </id>
        <property name="cardNum"/>
        <one-to-one name="person" class="Person"/>
    </class>
</hibernate-mapping>
Person.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 package="com.kaishengit.pojo">
    <class name="Person" table="t_person">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
        <one-to-one name="card"  class="Card" cascade="delete"/>
    </class>
</hibernate-mapping>

当one-to-one 的时候,默认属性为 fetch=”join”

多对一的 特例 (一对一)

这里写图片描述

<?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 package="com.kaishengit.pojo">
    <class name="Person" table="t_person">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
        <many-to-one name="card"  class="Card" unique="true"/>
    </class>
</hibernate-mapping>
多对多(三张表)
Teacher.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 package="com.kaishengit.pojo">
    <class name="Teacher" table="t_teacher">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
        <set name="studentSet" table="t_teacher_student">
            <key column="tea_id"/>
            <many-to-many class="Student" column="stu_id"/>
        </set>
    </class>
</hibernate-mapping>
Student.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 package="com.kaishengit.pojo">
    <class name="Student" table="t_student">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
        <set name="teacherSet" table="t_teacher_student" inverse="true">
            <key column="stu_id"/>
            <many-to-many class="Teacher" column="tea_id"/>
        </set>
    </class>
</hibernate-mapping>

t_teacher_student 为关系映射表

延迟加载

改变抓取策略 fetch=”join”
关闭延迟加载 lazy=“false”
预加载 Hibernate.initialize(object obj)

解决方案 在spring中实现
注解实现
User.java
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
@Entity
@Table(name = "user")
public class User {
    private int id;
    private String name;
    private Date birthday;
    private int age;
    private List<Address> set;
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
    // mappedBy address中User 的属性,为use放弃关系维护
    @Cascade(value = { CascadeType.SAVE_UPDATE, CascadeType.DELETE_ORPHAN,
            CascadeType.ALL })
    public List<Address> getSet() {
        return set;
    }
    public void setSet(List<Address> set) {
        this.set = set;
    }
    public User() {

    }
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    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;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
Address.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="address")
public class Address {
    private int id;
    private String info;
    private User user;
    public Address(){   
    }
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @Column(name="info")
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
    @ManyToOne
    @JoinColumn(name="user_id")
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

}

TABLE:使用一个特定的数据库表格来保存主键。
SEQUENCE:根据底层数据库的序列来生成主键,条件是数据库支持序列。
IDENTITY:主键由数据库自动生成(主要是自动增长型)
AUTO:主键由程序控制。

级联删除 我用的是
@Cascade(value = { CascadeType.REMOVE })
还有用下面这个的 他们用的都是
org.hibernate.annotations.CascadeType这个包
@Cascade(value = CascadeType.SAVE_UPDATE, CascadeType.DELETE_ORPHAN,CascadeType.ALL})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值