hibernate

hibernate

1. 导入依赖

<!-- https://mvnrepository.com/artifact/antlr/antlr -->
        <dependency>
            <groupId>antlr</groupId>
            <artifactId>antlr</artifactId>
            <version>2.7.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.geronimo.specs/geronimo-jta_1.1_spec -->
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-jta_1.1_spec</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate.common/hibernate-commons-annotations -->
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>5.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.10.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jboss/jandex -->
        <dependency>
            <groupId>org.jboss</groupId>
            <artifactId>jandex</artifactId>
            <version>2.0.0.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.18.1-GA</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jboss.logging/jboss-logging -->
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.3.0.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.7.Final</version>
        </dependency>
        <!-- 二级缓存包 -->
        <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.4.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>5.2.10.Final</version>
        </dependency>

        <dependency>
            <groupId>net.bytebuddy</groupId>
            <artifactId>byte-buddy</artifactId>
            <version>1.10.13</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator-annotation-processor -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator-annotation-processor</artifactId>
            <version>5.2.4.Final</version>
        </dependency>

2. 配置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.dialect"> org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/Long</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <!--  显示sql  -->
        <property name="show_sql">true</property>
        <!-- 自动执行ddl来创建或删除表结构 -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- hibernate.format_sql  sql语句格式化显示-->
        <property name="hibernate.format_sql">true</property>
        <!-- 配置RegionFactory为Ehcache的RegionFactory -->
        <!--<property name="hibernate.cache.use_second_level_cache">true</property>-->
        <!--<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>-->

       <!-- 引入指定实体类的映射文件 -->
       <!--<mapping package="ink.yql.model"/>-->
        <!-- 当使用注解时使用class 或 package属性 -->
        <mapping class="ink.yql.model.Teacher"/>
        <mapping class="ink.yql.model.School"/>
        <!-- <mapping resource="ink/yql/model/Teacher.hbm.xml"/> -->
        <!-- 二级缓存 -->
        <!-- 开启二级缓存 -->
        <!-- 配置RegionFactory为Ehcache的RegionFactory -->
        <!--<class-cache class="ink.yql.model.Teacher" usage="read-only"></class-cache>-->
    </session-factory>
</hibernate-configuration>

3. 创建实体类和hbm.xml文件

package ink.yql.model;

import org.hibernate.annotations.Table;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;


public class School implements Serializable {
    private Integer scid;
    private String scname;
    private String scaddress;
    private Set<Teacher> teachers = new HashSet<>();

    @Override
    public String toString() {
        return "School{" +
                  "scid=" + scid +
                  ", scname='" + scname + '\'' +
                  ", scaddress='" + scaddress + '\'' +
                  '}';
    }

    public Integer getScid() {
        return scid;
    }

    public void setScid(Integer scid) {
        this.scid = scid;
    }

    public String getScname() {
        return scname;
    }

    public void setScname(String scname) {
        this.scname = scname;
    }

    public String getScaddress() {
        return scaddress;
    }

    public void setScaddress(String scaddress) {
        this.scaddress = scaddress;
    }

    public Set<Teacher> getTeachers() {
        return teachers;
    }

    public void setTeachers(Set<Teacher> teachers) {
        this.teachers = teachers;
    }

    public School() {
    }

    public School(Integer scid, String scname, String scaddress, Set<Teacher> teachers) {
        this.scid = scid;
        this.scname = scname;
        this.scaddress = scaddress;
        this.teachers = teachers;
    }
}
<?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 table="school" name="ink.yql.model.School">
        <!-- 每个class 必须指定一个id 主键列 : 唯一标识 -->
        <id name="scid" column="sc_id">
            <generator class="identity"/>
        </id>
        <property name="scname" column="sc_name"/>
        <property name="scaddress" column="sc_address"/>
        <!-- one-to-many 一对多 
			many-to-one 多对一
			one-to-one 一对一
		-->
        <set name="teachers" >
            <key column="sc_id"/>
            <one-to-many class="ink.yql.model.Teacher"/>
        </set>
    </class>
</hibernate-mapping>

4. 使用hibernate

// 创建  Configuration对象调用configure方法加载hibernate.cfg.xml 文件
 Configuration  config = new Configuration();
 config.configure();
// 获取sessionFactory对象
  SessionFactory  factory = config.buildSessionFactory();
// 获取session 
  Session         session = factory.openSession();
// 获取当前session连接的事务 8
  Transaction    transaction = session.beginTransaction();

    Criteria query1 = session.createCriteria(School.class);
	Query query2 = session.createQuery("from School");
	// 查询所有
	query1.list();
	// 查询所有
	query2.list();
	//查询一个
	session.get(School.class,1);
	//添加一个
	session.save(new School());
	//删除一个
	session.delete(School.class,1);
	// 更新一个
	session.update(new School);
		 session.flush();
        transaction.commit();
        session.close();
        factory.close();

5. 一级缓存

默认使用的是一级缓存,及同一个session中不提交事务,不刷新session,不关闭session,是一级缓存

6. 二级缓存

添加一个ehcache.xml文件在scr下

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache>
    <!-- Sets the path to the directory where cache .data files are created.
    设置缓存文件被创建的目录路径
     If the path is a Java System Property it is replaced by
     its value in the running VM.
     如果这个路径是Java System Property,那么这个路径就会被这个属性值所替代
     The following properties are translated:
     user.home - User's home directory
     user.dir - User's current working directory
     java.io.tmpdir - Default temp file path -->

    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required:

        maxElementsInMemory            - Sets the maximum number of objects that will be created in memory
                                        设置内存中创建的最大对象个数
        eternal                                     - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element is never expired.
                                                    设置元素是否永恒,如果永恒,那么将忽略超时限制并且该元素永远不会过期
        overflowToDisk                      - Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit.
                                            设置在内存中的缓存达到打到最大的对象数时是否允许溢出到磁盘

        The following attributes are optional:
        timeToIdleSeconds            -     Sets the time to idle for an element before it expires.
                                        设置元素过期之前的空闲时间
                                                        i.e. The maximum amount of time between accesses before an
                                                        element expires Is only used if the element is not eternal.
                                                        Optional attribute. A value of 0 means that an Element can idle
                                                        for infinity.The default value is 0.
        timeToLiveSeconds              - Sets the time to live for an element before it expires.
                                        设置元素过期之前的时间
                                                         i.e. The maximum time between creation time and when an element
                                                         expires.  Is only used if the element is not eternal.
                                                         Optional attribute. A value of 0 means that and Element can live
                                                         for infinity.
                                                        The default value is 0.
        diskPersistent                           - Whether the disk store persists between restarts of the Virtual Machine.
                                                    在重启虚拟机后磁盘存储是否还存在
                                                         The default value is false.
        diskExpiryThreadIntervalSeconds   - The number of seconds between runs of the disk expiry thread.
                                            磁盘失效线程之间的运行秒数。
                                                         The default value  is 120 seconds.
        -->
    <diskStore path="/data/ehcache"/>
    <defaultCache maxElementsInMemory="10000" eternal="false"
                  overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="180"
                  diskPersistent="false" diskExpiryThreadIntervalSeconds="60" />
    <cache name="org.hibernate.cache.StandardQueryCache"
           maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300"
           timeToLiveSeconds="4200" overflowToDisk="true" />
    <cache name="org.hibernate.cache.UpdateTimestampsCache"
           maxElementsInMemory="5000" eternal="true" timeToIdleSeconds="0"
           timeToLiveSeconds="0" overflowToDisk="false" />
</ehcache>

hibernate.cfg.xml文件

   <!-- 配置RegionFactory为Ehcache的RegionFactory -->
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
  <!-- 开启二级缓存 -->
        <!-- 配置RegionFactory为Ehcache的RegionFactory -->
        <class-cache class="ink.yql.model.Teacher" usage="read-only"></class-cache>

在要开启二级缓存的hbm.xml中添加

<cache usage="read-only"></cache>

7. 注解

hibernate.cfg.xml中使用class或package属性

		<mapping class="ink.yql.model.Teacher"/>
        <mapping class="ink.yql.model.School"/>

在实体类型

// Entity 和Table 作用在类上,表明这个类是表的实体类
@Entity()
// name 属性是 数据库的表名
@Table(name = "school")
@Id // 使用在主键上
@GeneratedValue // 主键策略,设置strategy属性
@Column(name = "sc_id") // 作用在属性上,表名这个属性对应的字段
@OneToMany(targetEntity = Teacher.class) // 一对多
@ManyToOne(targetEntity = Teacher.class) // 多对一
@OneToOne() // 一对一
@JoinColumn(name = "sc_id") // 一对一或多对一时使用指定外键
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值